//死锁情况
/**
两个锁的相互嵌套。
两个线程分别进行。
*/
class Test implements Runnable
{
private boolean flag;
Test(boolean flag)
{
this.flag = flag;
}
public void run()
{
if (flag)
{
synchronized(MyLock.locka)
{
System.out.println(Thread.currentThread().getName()+"...if locka");
synchronized (MyLock.lockb)
{
System.out.println(Thread.currentThread().getName()+"...if lockb");
}
}
}
else
{
synchronized(MyLock.lockb)
{
System.out.println(Thread.currentThread().getName()+"...else locka");
synchronized (MyLock.locka)
{
System.out.println(Thread.currentThread().getName()+"...else lockb");
}
}
}
}
}
class MyLock
{
public static final Object locka = new Object();
public static final Object lockb = new Object();
}
class DeadLockDemo
{
public static void main(String[] args)
{
Test a1 = new Test(true);
Test a2 = new Test(false);
Thread t1 = new Thread(a1);
Thread t2 = new Thread(a2);
t1.start();
t2.start();
}
}
/**
两个锁的相互嵌套。
两个线程分别进行。
*/
class Test implements Runnable
{
private boolean flag;
Test(boolean flag)
{
this.flag = flag;
}
public void run()
{
if (flag)
{
synchronized(MyLock.locka)
{
System.out.println(Thread.currentThread().getName()+"...if locka");
synchronized (MyLock.lockb)
{
System.out.println(Thread.currentThread().getName()+"...if lockb");
}
}
}
else
{
synchronized(MyLock.lockb)
{
System.out.println(Thread.currentThread().getName()+"...else locka");
synchronized (MyLock.locka)
{
System.out.println(Thread.currentThread().getName()+"...else lockb");
}
}
}
}
}
class MyLock
{
public static final Object locka = new Object();
public static final Object lockb = new Object();
}
class DeadLockDemo
{
public static void main(String[] args)
{
Test a1 = new Test(true);
Test a2 = new Test(false);
Thread t1 = new Thread(a1);
Thread t2 = new Thread(a2);
t1.start();
t2.start();
}
}