using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
class Program
{
static void Main(string[] args)
{
Add add1 = new Add ();
Thread thread1 = new Thread (new ThreadStart (add1 .ThreadProc));
Thread thread2 = new Thread(new ThreadStart(add1.ThreadProc));
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
Console.WriteLine(add1.Result);
Console.ReadLine();
}
}
class Add
{
protected int a = 0;
protected void Update()
{
Monitor.Enter(this);
a++;
}
public int Result
{
get
{
return a;
}
}
public void ThreadProc()
{
for (int n = 0; n < 10; n++)
{
Update();
}
}
}
原理其实很简单,就是在进程thread1进行时占用a的使用权(通过Monitor.Enter(this)实现),然后故意不使用Monitor.Exit(this)释放使用权,这样,进程thread2在进行时需要使用a,但是,由于a已经进入了Monitor类的保护区,造成进程thread2无法访问,必须等待的状况,而同时,由于缺少了Monitor.Exit()的实现,a的使用权是不会被释放的,进程thread2一直等待,造成了死锁deadlock.