C# 多线程 lock 实例
class Program { static void Main(string[] args) { //在t1线程中调用LockMe,并将deadlock设为true(将出现死锁) int i = 10; while (i > 0) { Thread t1 = new Thread(LockMe); t1.Start(true); Thread.Sleep(1000); Console.WriteLine(string.Format("1.i:{0},开始调用LockMe :{1}",i, System.DateTime.Now)); i = i - 1; } Console.ReadLine(); } public static object locker = new object(); public static void LockMe(object o) { lock (locker) { Console.WriteLine(string.Format("2. 我是锁定的 :{0}", System.DateTime.Now)); Thread.Sleep(2000); } } } 一定要把 锁的对象 public static object locker = new object(); 写在方法外边, 如果按照下面的写法则不起作用 public static void LockMe(object o) { object locker = new object(); lock (locker) { Console.WriteLine(string.Format("2. 我是锁定的 :{0}", System.DateTime.Now)); Thread.Sleep(2000); } } ============================================ class Program { static void Main(string[] args) { C1 c1 = new C1(); //在t1线程中调用LockMe,并将deadlock设为true(将出现死锁) int i = 10; while (i > 0) { Thread t1 = new Thread(c1.LockMe); t1.Start(true); Thread.Sleep(1000); Console.WriteLine(string.Format("1.i:{0},开始调用LockMe :{1}",i, System.DateTime.Now)); i = i - 1; } //在主线程中lock c1 //lock (c1) //{ // //调用没有被lock的方法 // c1.DoNotLockMe(); // //调用被lock的方法,并试图将deadlock解除 // c1.LockMe(true); //} Console.ReadLine(); } } } class C1 { //private bool deadlocked = true; //private object locker = new object(); ////这个方法用到了lock,我们希望lock的代码在同一时刻只能由一个线程访问 //public void LockMe(object o) //{ // lock (this) // { // while (deadlocked) // { // deadlocked = (bool)o; // Console.WriteLine("Foo: 我是锁定的 :("); // Thread.Sleep(500); // } // } //} private bool deadlocked = true; private object locker = new object(); //这个方法用到了lock,我们希望lock的代码在同一时刻只能由一个线程访问 public void LockMe(object o) { lock (locker) { //while (deadlocked) //{ //deadlocked = (bool)o; Console.WriteLine(string.Format("2. 我是锁定的 :{0}",System.DateTime.Now)); Thread.Sleep(2000); //} } } //所有线程都可以同时访问的方法 public void DoNotLockMe() { Console.WriteLine("我是未被锁定 :)"); } }