当两个线程争夺两个互斥、独占的资源时很容易发生死锁。
根据这个原理可以用C#描绘出死锁的情况。
class Program
{
/// <summary>
/// 连个资源对象
/// </summary>
static object res1 = new object ( );
static object res2 = new object ( );
/// <summary>
/// 死锁标志
/// </summary>
public static int flag = 0;
static void Main ( string [ ] args )
{
//启动两个线程进行资源竞争
System. Threading. Thread t1 = new System. Threading. Thread ( Thread1 );
System. Threading. Thread t2 = new System. Threading. Thread ( Thread2 );
DateTime dt1 = DateTime. Now;
t1. Start ( );
t2. Start ( );
while ( true )
{
int count = flag;
System. Threading. Thread. Sleep ( 0 );
//如果两个线程处于相斥阶段,则发生死锁。
if ( count == flag )
{
DateTime dt2 = DateTime. Now;
TimeSpan ts1 = new TimeSpan ( dt1. Ticks );
TimeSpan ts2 = new TimeSpan ( dt2. Ticks );
Console. WriteLine ( "哎,死锁啦!用时:"+ts2.Subtract(ts1).Duration().Milliseconds.ToString()+" 毫秒.");
}
}
}
/// <summary>
/// 先锁定”资源1“,然后是锁定 “资源2”
/// </summary>
private static void Thread1 ( )
{
while ( true )
{
System. Threading. Monitor. Enter ( res2);
System. Threading. Monitor. Enter ( res1);
flag++;
System. Threading. Monitor. Exit ( res1 );
System. Threading. Monitor. Exit ( res2 );
}
}
/// <summary>
/// 先锁定”资源2“,然后是锁定 “资源1”
/// </summary>
private static void Thread2 ( )
{
while ( true )
{
System. Threading. Monitor. Enter ( res1 );
System. Threading. Monitor. Enter ( res2 );
flag++;
System. Threading. Monitor. Exit ( res2 );
System. Threading. Monitor. Exit ( res1 );
}
}
}
线程1锁定资源2,然后向获得资源1的锁,线程2正好相反。这时候就产生了死锁。
Monitor.TryEnter(,);
可以比较宽容的加锁在一定的时间段内。