不通过调用下面的自定义类,为什么我这样写 就锁不住了呢?
class Test implements Runnable
{
Object locka = new Object();
Object lockb = new Object();
private boolean flag;
Test(boolean flag)
{
this.flag = flag;
}
public void run()
{
if(flag)
{
while(true)
{
synchronized(locka)//毕老师视屏里的是通过调用下面的MyLock.locka,
{
System.out.println("locka");
synchronized(lockb)
{
System.out.println("lockb");
}
}
}
}
else
{
while(true)
{
synchronized(lockb)
{
System.out.println("else lockb");
synchronized(locka)
{
System.out.println("else locka");
}
}
}
}
}
}
class MyLock
{
static Object locka = new Object();
static Object lockb = new Object();
}
class MyDeadLock
{
public static void main(String[] args)
{
Test t1 = new Test(true);
Test t2 = new Test(false);
Thread t3 = new Thread(t1);
Thread t4 = new Thread(t2);
t3.start();
t4.start();
}
} |
|