//线程0运行时,拿不到线程1的锁没有办法在进行下去。
//线程1运行时,拿不到线程0的锁也没有办法在运行下去了
//两者谁碰到谁都可以就会发生死锁现象。
class Demo implements Runnable
{
private boolean flag;
Demo(boolean flag){//贝尔类型输出划
this.flag = flag;
}
public void run()
{
if(flag)
{
while(true)
synchronized(ThLock.lock_a)
{
System.out.println("if:线程:"+Thread.currentThread().getName()+"两个杠杠");
synchronized(ThLock.lock_b)
{
System.out.println("if:线程:"+Thread.currentThread().getName()+"一个杠杠");
}
}
}
else
{
while(true)
synchronized(ThLock.lock_b)
{
System.out.println("else:线程:"+Thread.currentThread().getName()+"四个杠杠");
synchronized(ThLock.lock_a)
{
System.out.println("else:线程:"+Thread.currentThread().getName()+"三个杠杠");
}
}
}
}
}
//创建一个类 ,用来创建两个锁
class ThLock
{
public static final Object lock_a = new Object();
public static final Object lock_b = new Object();
}
class DeadLock
{
public static void main(String[] args)
{
Demo t = new Demo(true);
Demo t1 = new Demo(false);
Thread Th1 = new Thread(t);
Thread Th2 = new Thread(t1);
Th1.start();
Th2.start();
}
} |
|