思索就是两把锁相互调用,一种情况是同步嵌套,如下,写程序的时候要理清思路,注意观察,尽量避免这种情况的发生
class Test implements Runnable
{
private boolean flag = true;
Test(boolean flag)
{
this.flag = flag;
}
public void run()
{
while(true)
{
if(flag)
{
synchronized(MyLock.lock_a)
{
System.out.println(Thread.currentThread().getName()+"..if lock_a");
synchronized(MyLock.lock_b)
{
System.out.println(Thread.currentThread().getName()+"..if lock_b");
}
}
}
else
{
synchronized(MyLock.lock_b)
{
System.out.println(Thread.currentThread().getName()+"..else lock_b");
synchronized(MyLock.lock_a)
{
System.out.println(Thread.currentThread().getName()+"..else lock_a");
}
}
}
}
}
}
class MyLock
{
public static Object lock_a = new Object();
public static Object lock_b = new Object();
}
class DeadLockTest
{
public static void main(String[] args)
{
Test t1 = new Test(true);
Test t2 = new Test(false);
new Thread(t1).start();
new Thread(t2).start();
}
}
|