C#多线程之互斥

来源:互联网 发布:淘宝白菜群怎么赚钱 编辑:程序博客网 时间:2024/06/02 02:34
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace MutexTest{    class MutexTest    {        static object m_lock = new object();        static void Main(string[] args)        {            Mutex m = new Mutex();            Thread t1 = new Thread(new ParameterizedThreadStart(Thread1));            t1.IsBackground = true;            t1.Start(m);            Thread t2 = new Thread(new ParameterizedThreadStart(Thread2));            t2.IsBackground = true;            t2.Start(m);            Console.ReadLine();                    }        static void Thread1(object obj)        {            Mutex m = obj as Mutex;            while (true)            {                m.WaitOne();                WriteLine("In Thread-1");                m.ReleaseMutex();                Thread.Sleep(100);            }        }        static void Thread2(object obj)        {            Mutex m = obj as Mutex;            while (true)            {                m.WaitOne();                WriteLine("In Thread-----------2");                m.ReleaseMutex();                Thread.Sleep(1000);            }        }        static void WriteLine(string msg)        {            lock (m_lock)            {                Console.WriteLine(msg);            }        }    }}

原创粉丝点击