class Test implements Runnable
{
private boolean flag;
Object locka=new Object();
Object lockb=new Object();
Test(boolean flag)
{
this.flag=flag;
}
public void run()
{
if(flag)
{while(true)
{synchronized (locka)
{
System.out.println("if locka");
synchronized (lockb)
{ try
{
Thread.sleep(10);
}
catch (Exception e)
{
}
System.out.println("if lockb");
}
}
}
}
else
{while(true)
{
synchronized (lockb)
{
System.out.println("else lockb");
synchronized (locka)
{
try
{
Thread.sleep(10);
}
catch (Exception e)
{
}
System.out.println("else locka");
}
}
}
}
}
}
/*class MyLock
{
static Object locka=new Object();
static Object lockb=new Object();
}*/
class Demo2
{public static void main(String[] args)
{
Thread t1=new Thread(new Test(true));
Thread t2=new Thread(new Test(false));
t1.start();
t2.start();
}
}
为什么两个锁定义在本类中不出现死锁,而单独在另一个类定义的两个锁却可以出现死锁? |
|