Mutex作用,例子,大家看了明白

来源:互联网 发布:springmvc源码 编辑:程序博客网 时间:2024/05/22 02:26

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.Add(Program.student.Count + 1);

            Console.WriteLine(" 第二个线程加{0}", Program.student.Count);

            mutex.ReleaseMutex();
           

        }

    }

原创粉丝点击