//创建一个死锁程序,采用同步中嵌套同步的方式
class LockBase implements Runnable
{
static Object obj1=new Object();
static Object obj2=new Object();
/*若obj1,obj2均用private修饰,则t1和t2中的obj1,obj2不同,不构成死锁
静态成员随着类的加载而存在于内存的方法区中,为共享数据;
私有成员随着对象的建立而存在,属于不同对象。
*/
private boolean flag;
LockBase(boolean flag)
{
this.flag=flag;
}
public void run()
{
if(flag)
{
for (;;)
{
synchronized(obj1)
{
System.out.println(Thread.currentThread().getName()+"...Aobj1..run");
synchronized(obj2)
{
System.out.println(Thread.currentThread().getName()+"...Aobj2..run");
}
}
}
}
else
for (;;)
{
synchronized(obj2)
{
System.out.println(Thread.currentThread().getName()+"...Bobj2..run");
synchronized(obj1)
{
System.out.println(Thread.currentThread().getName()+"...Bobj1..run");
}
}
}
}
}
class LockDeadDemo
{
public static void main(String [] args)
{
Thread t1=new Thread(new LockBase(true));
Thread t2=new Thread(new LockBase(false));
t1.start();
t2.start();
}
}
|
|