Test Thread Lock - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Thread

Description

Test Thread Lock

Demo Code

using System;//w w w.j  a  v  a 2  s.  c  o m
using System.Threading;
public class ThreadLockTest {
   private int[]   m_Array = new int[10];
   private int      m_CurrentIndex = 0;
   public  void ThreadProc( ) {
      int ThreadId = Thread.CurrentThread.GetHashCode( );
      for( int i = 0; i < 10; i++ )
      {
         lock( this )
         {
            if( m_CurrentIndex < 10 ) {
               Thread.Sleep( (new Random()).Next( 2 ) * 1000 );
               m_Array[m_CurrentIndex++] = ThreadId;
            }
         }
      }
   }
   public void PrintArray( ) {
      for( int i = 0; i < 10; i++ )
         Console.WriteLine( "m_Array[{0}] = {1}", i, m_Array[i] );
      }
      public static void Main( ) {
         ThreadLockTest tlt = new ThreadLockTest( );
         Thread t1 = new Thread( new ThreadStart( tlt.ThreadProc ) );
         Thread t2 = new Thread( new ThreadStart( tlt.ThreadProc ) );
         t1.Start( );
         t2.Start( );
         t1.Join( );
         t2.Join( );
         tlt.PrintArray( );
      }
}

Result


Related Tutorials