Monitor Mutex Semaphore

public class Test 
{
   private Monitor sync = new Monitor();
   
   public void Method1()
   {
      sync.Enter();
      try {
         // critical section
         Console.WriteLine("Method1");   
      }
      finally {
         sync.Exit();
      }
   }

   public void Method2()
   {   
      sync.Enter();
      try {
         // critical section 
         Console.WriteLine("Method2");
      }
      finally {
         sync.Exit(); 
      }
   }
}

static void Main(string[] args)
{
   Test test = new Test();

   Thread t1 = new Thread(() => {
      test.Method1();
   });

   Thread t2 = new Thread(() => {   
      test.Method2();
   });

   t1.Start();
   t2.Start();

   t1.Join();
   t2.Join();
}
static Mutex mutex = new Mutex();

static void Method1()
{
   mutex.WaitOne();

   // critical section
   Console.WriteLine("Method1");

   mutex.ReleaseMutex();
}

static void Method2()
{
   mutex.WaitOne();

   // critical section   
   Console.WriteLine("Method2");

   mutex.ReleaseMutex();
}

static void Main(string[] args)
{
   Thread t1 = new Thread(Method1);
   Thread t2 = new Thread(Method2);

   t1.Start();
   t2.Start();

   t1.Join();
   t2.Join();
}
static Semaphore semaphore = new Semaphore(1, 1);

static void Method1()
{
   semaphore.WaitOne();

   // critical section
   Console.WriteLine("Method1");

   semaphore.Release();  
}

static void Method2() 
{
   semaphore.WaitOne();

   // critical section
   Console.WriteLine("Method2");

   semaphore.Release();
}

static void Main(string[] args)
{
   Thread t1 = new Thread(Method1);
   Thread t2 = new Thread(Method2);

   t1.Start();  
   t2.Start();

   t1.Join();
   t2.Join();
}

你可能感兴趣的:(c#,多线程)