home *** CD-ROM | disk | FTP | other *** search
/ io Programmo 40 / IOPROG_40.ISO / SOFT / NETFrameworkSDK.exe / comsdk.cab / samples.exe / Threading / Thread / CS_Sample / SyncOne.cs < prev    next >
Encoding:
Text File  |  2000-06-23  |  1.4 KB  |  55 lines

  1. using System;
  2. using System.Threading;
  3.  
  4. public class Alpha
  5. {
  6.  
  7.     // The method that will be called when the thread is started
  8.     public void Beta()
  9.     {
  10.         int        iThreadID    = Thread.CurrentThread.GetHashCode( );
  11.         int        cLoop        = 100;
  12.         while((cLoop--)>0)
  13.         {
  14.             // Obtain the lock
  15.             Monitor.Enter(this);
  16.             Console.Write("{0} Thread, ",Thread.CurrentThread.Name);
  17.             Console.WriteLine("Hash: {0}, Hello!",iThreadID);
  18.             // Release the lock
  19.             Monitor.Exit(this);
  20.         }
  21.     }
  22. };
  23.  
  24. public class Simple
  25. {
  26.     public static int Main(String[] args)
  27.     {
  28.         Console.WriteLine("Thread Sync One Sample");
  29.         Alpha        oAlpha        = new Alpha( );
  30.  
  31.         // Create the 1st thread object, passing in the Alpha.Beta method
  32.         // via a ThreadStart delegate
  33.         Thread        oThread1    = new Thread(new ThreadStart(oAlpha.Beta));
  34.         oThread1.Name = "Yellow";
  35.  
  36.         // Start the 1st thread
  37.         oThread1.Start( );
  38.  
  39.         // Spin waiting for the started thread to become alive
  40.         while(!oThread1.IsAlive)   ;
  41.  
  42.         // Create the 2nd thread object, passing in the Alpha.Beta method
  43.         // via a ThreadStart delegate, on the same oAlpha instance
  44.         Thread        oThread2    = new Thread(new ThreadStart(oAlpha.Beta) );
  45.         oThread2.Name = " Green";
  46.  
  47.         // Start the 2nd thread
  48.         oThread2.Start( );
  49.  
  50.         // Spin waiting for the started thread to Start
  51.         while(oThread2.ThreadState==ThreadState.Unstarted)  ;
  52.  
  53.         return 0;
  54.     }
  55. };