今天在MSDN上看到了Lock的定义“lock 关键字将语句块标记为临界区,方法是获取给定对象的互斥锁,执行语句,然后释放该锁。”
如:
Object thisLock = new Object();
lock (thisLock)
{
// Critical code section
}
从这个解释看来,只要{}中的代码跑完了,线程就会释放锁。
但是运行了如下代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Tool t1 = new Tool("Book");
Tool t2 = new Tool("Pen");
Student a = new Student("A", t1, t2);
Student b = new Student("B", t2, t1);
Thread ta = new Thread(new ThreadStart(a.Run));
Thread tb = new Thread(new ThreadStart(b.Run));
ta.Start();
tb.Start();
}
}
public class Tool
{
public string Name;
public Tool(string Name){this.Name = Name;}
}
class Student
{
private string Name;
private Tool Tool1;
private Tool Tool2;
public Student(string Name, Tool tool1, Tool tool2)
{
this.Name = Name; this.Tool1 = tool1; this.Tool2 = tool2;
}
public void Run()
{
while (true) Study();
} private void Study()
{
lock (Tool1)//得到并锁住工具1
{
Console.WriteLine("{0} get {1}"+Thread.CurrentThread.Name, Name, Tool1.Name);
lock (Tool2)//得到并锁住工具2
{
Console.WriteLine("{0} get {1}", Name, Tool2.Name);
Console.WriteLine("{0} Will Study", Name);//得到工具并学习
Console.WriteLine("{0} Dorp {1}", Name, Tool1.Name); //释放工具1
}
Console.WriteLine("{0} Dorp {1}", Name, Tool2.Name); //释放工具2
}
}
}
}
结果是:
A get Book
B get Pen
实在是不理解,将上面的lock (Tool1)换成lock (this)后,结果不一样了。
请问lock (...)中的参数有什么用。看了MSDN感觉没什么特别的用途吗?
各位高手指点一下!
如:
Object thisLock = new Object();
lock (thisLock)
{
// Critical code section
}
从这个解释看来,只要{}中的代码跑完了,线程就会释放锁。
但是运行了如下代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Tool t1 = new Tool("Book");
Tool t2 = new Tool("Pen");
Student a = new Student("A", t1, t2);
Student b = new Student("B", t2, t1);
Thread ta = new Thread(new ThreadStart(a.Run));
Thread tb = new Thread(new ThreadStart(b.Run));
ta.Start();
tb.Start();
}
}
public class Tool
{
public string Name;
public Tool(string Name){this.Name = Name;}
}
class Student
{
private string Name;
private Tool Tool1;
private Tool Tool2;
public Student(string Name, Tool tool1, Tool tool2)
{
this.Name = Name; this.Tool1 = tool1; this.Tool2 = tool2;
}
public void Run()
{
while (true) Study();
} private void Study()
{
lock (Tool1)//得到并锁住工具1
{
Console.WriteLine("{0} get {1}"+Thread.CurrentThread.Name, Name, Tool1.Name);
lock (Tool2)//得到并锁住工具2
{
Console.WriteLine("{0} get {1}", Name, Tool2.Name);
Console.WriteLine("{0} Will Study", Name);//得到工具并学习
Console.WriteLine("{0} Dorp {1}", Name, Tool1.Name); //释放工具1
}
Console.WriteLine("{0} Dorp {1}", Name, Tool2.Name); //释放工具2
}
}
}
}
结果是:
A get Book
B get Pen
实在是不理解,将上面的lock (Tool1)换成lock (this)后,结果不一样了。
请问lock (...)中的参数有什么用。看了MSDN感觉没什么特别的用途吗?
各位高手指点一下!
每个Student.run中的lock 锁定的是 自己对象内部的Tool1,Tool2吧 Tool1,Tool2 设置成全局的看看