class LockDemo
{
static LockDemo L1=new LockDemo();
static LockDemo L2=new LockDemo();
}
class Demo implements Runnable
{
Object obj1=new Object();
Object obj2=new Object();
private boolean flag;
Demo( boolean flag
{
this.flag=flag;
}
public void run()
{
if (flag)
{
synchronized(obj1)
{
System.out.println("if L1");
synchronized(obj2)
{
System.out.println("if L2");
}
}
}
else
{
synchronized(obj2)
{
System.out.println("else L2");
synchronized(obj1)
{
System.out.println("else L1");
}
}
}
}
}
class DeadLockDemo
{
public static void main(String[] args)
{
new Thread(new Demo(false)).start();
new Thread(new Demo(true)).start();
}
}
在学毕老师视频,我想问一下,当是锁里面的对象是 obj1 obj2时不会出现死锁现象,else L2 if L1 else L1 if L2 4个都能打印出来
而使用LockDemo.L1 Lock.L2时就会出现死锁现象,这是为什么呢?
|