class DeadLock implements Runnable
{
//定义两个锁
private static Object lockA = new Object();
private static Object lockB = new Object();
private boolean flag;
DeadLock(boolean flag)
{
this.flag = flag;
}
//覆写Runnable接口的run()方法
public void run()
{
while(true)
{
if(flag)
{ //A锁嵌套B锁
synchronized(lockA)
{
System.out.println("if lockA");
synchronized(lockB)
{
System.out.println("if lockB");
}
}
}
else
{ // B锁嵌套A锁
synchronized(lockB)
{
System.out.println("else lockB");
synchronized(lockA)
{
System.out.println("else lockA");
}
}
}
}
}
class DeadLockTest
{
public static void main(String[] args)
{
DeadLock dl1 = new DeadLock(true);
DeadLock dl2 = new DeadLock(false);
Thread t1 = new Thread(dl1);
Thread t2 = new Thread(dl2);
t1.start();
t2.start();
}
} |
|