System.Threading.Mutex :同步基元,它只向一个线程授予对共享资源的独占访问权。当有两个或两个以上的线程要对一个共享资源进行操作的时候,就要

System.Threading.Mutex互斥体来进行调节。保证只有一个线程可以对共享资源进行控制。如果一个线程获得了互斥体,其他线程只能在第一个线程放弃互斥体之前先挂起。互斥体可以通过waitone()请求相同的互斥体而不会阻塞其执行

但必须在使用后ReleaseMutex来释放互斥体。

下边是示例代码

 

 

using System;

using System.Collections.Generic;

using System.Text;

using System.Threading;

using System.Collections;

 

namespace ConsoleApplication19

{

    

     class Program

     {

         public static ArrayList student = new ArrayList();

         public static bool flag = false;

         static void Main(string[] args)

         {

              Thread schooladd = new Thread(students.Add);

              schooladd.Start();

              Thread schoolreduce = new Thread(students.Reduce);

              schoolreduce.Start();

              string d = Console.ReadLine();

}

     }

     class students

     {

         public static System.Threading.Mutex mutex = new System.Threading.Mutex(false,null/*"Program.student"*/, out Program.flag);//null是互斥体的名字可以是任何值

         public static void Add()

         {

              mutex.WaitOne();

              Program.student.Add(new students());

              Console.WriteLine("现在学校里有{0}:名学生", Program.student.Count);

             mutex.ReleaseMutex();

         }

         public static void Reduce()

         {

mutex.WaitOne();//保证了在该线程没有ReleaseMutex之前没有其他线程可以对Program.student进行访问

 

              Program.student.RemoveAt(Program.student.Count-1);

                   Console.WriteLine("现在学校里有{0}:名学生", Program.student.Count);

              mutex.ReleaseMutex();

         }

     }

}