class Dea implements Runnable
{
//定义一个标记
private boolean flag;
//初始化
Dea(boolean flag)
{
this.flag = flag;
}
//覆盖Run方法
public void run()
{
//创建同步锁,并互相嵌套
if(flag)
{
synchronized(Lock.lockA)
{
System.out.println("Lock.lockA");
synchronized(Lock.lockB)
{
System.out.println("Lock.lockB");
}
}
}
else
{
synchronized(Lock.lockB)
{
System.out.println("Lock.lockB");
synchronized(Lock.lockA)
{
System.out.println("Lock.lockA");
}
}
}
}
}
//创建锁对象
//加static:原因是可以直接用类名.lock访问
class Lock
{
static Object lockA = new Object();
static Object lockB = new Object();
}
public class _09死锁创建 {
public static void main(String[]args)
{
Thread t1 = new Thread(new Dea(true));
Thread t2 = new Thread(new Dea(false));
t1.start();
t2.start();
}
}