class Test
{
public static void main(String[] args)
{
Demo d1=new Demo(true);
Demo d2=new Demo(false);
Thread t1=new Thread(d1);
Thread t2=new Thread(d2);
t1.start();
t2.start();
}
}
class MyLock
{
public static final Object locka=new Object();
public static final Object lockb=new Object();
}
class Demo implements Runnable
{
private boolean flag;
private int num=100;
public Demo(boolean flag)
{
this.flag=flag;
}
public void run()
{
if(this.flag)
{
while(true)
{
synchronized(MyLock.locka)
{
System.out.println(Thread.currentThread().getName()+"...if...locka-->num::"+this.num--);
synchronized(MyLock.lockb)
{
System.out.println(Thread.currentThread().getName()+"...if...lockb-->num::"+this.num--);
}
}
}
}
else
{
while(true)
{
synchronized(MyLock.lockb)
{
System.out.println(Thread.currentThread().getName()+"...else...lockb-->num::"+this.num--);
synchronized(MyLock.locka)
{
System.out.println(Thread.currentThread().getName()+"...else...locka-->num::"+this.num--);
}
}
}
}
}
}
当t1线程手持A锁,要B锁时,此时,刚刚好线程t2手持B锁要A锁。双方均等的对方锁的释放。出现死锁情况。