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

  1. using System;
  2. using System.Threading;
  3.  
  4. public class Gamma
  5. {
  6. };
  7.  
  8. public class Alpha
  9. {
  10.     public Gamma    oGamma;
  11.  
  12.     public void Beta( )
  13.     {
  14.         //    Obtain the lock
  15.         Monitor.Enter(oGamma);
  16.  
  17.         int        cLoop    = 10;
  18.         while ((cLoop--) > 0)
  19.         {
  20.             Console.Write(" Hello");
  21.  
  22.             //    Release the lock and wait to be Notified
  23.             Monitor.Wait(oGamma);
  24.  
  25.             //    Signal for next thread in wait queue to proceed
  26.             Monitor.Pulse(oGamma);
  27.         }
  28.  
  29.         //    Release the lock
  30.         Monitor.Exit(oGamma);
  31.     }
  32. };
  33.  
  34. public class Delta
  35. {
  36.     public Gamma    oGamma;
  37.  
  38.     public Delta(Gamma G)
  39.     {
  40.         oGamma = G;
  41.     }
  42.  
  43.     public void Beta( )
  44.     {
  45.         //    Obtain the lock
  46.         Monitor.Enter(oGamma);
  47.  
  48.         int        cLoop    = 10;
  49.         while((cLoop--) > 0)
  50.         {
  51.             Console.WriteLine(" World");
  52.             //    Signal for next thread in wait queue to proceed
  53.             Monitor.Pulse(oGamma);
  54.  
  55.             //    Release the lock and wait to be Notified
  56.             Monitor.Wait(oGamma);
  57.         }
  58.  
  59.         //    Release the lock
  60.         Monitor.Exit(oGamma);
  61.     }
  62. };
  63.  
  64. public class Simple
  65. {
  66.     public static int Main(String[] args)
  67.     {
  68.         Console.WriteLine("Thread Sync Two Sample");
  69.  
  70.         Gamma    oGamma        = new Gamma( );
  71.  
  72.         Alpha    oAlpha        = new Alpha( );
  73.         oAlpha.oGamma = oGamma;
  74.  
  75.         //    Create the 1st thread object, passing in the oAlphaBeta method
  76.         //    via a ThreadStart delegate
  77.         Thread    Thread1        = new Thread(new ThreadStart(oAlpha.Beta) );
  78.  
  79.         //    Start the 1st thread
  80.         Thread1.Start( );
  81.         while(!Thread1.IsAlive);
  82.  
  83.         Delta    oDelta        = new Delta(oGamma);
  84.  
  85.         //    Create the 2nd thread object, passing in the oDelta.Beta method
  86.         //    via a ThreadStart delegate, on the new oDelta instance
  87.         Thread    Thread2        = new Thread(new ThreadStart(oDelta.Beta) );
  88.  
  89.         //    Start the 2nd thread
  90.         Thread2.Start( );
  91.  
  92.         return 0;
  93.     }
  94. };