/*
目的:自己写一个由于同步嵌套引起的死锁!
思路:多个线程在执行时,某一时刻,0-Thread绑定了LockA锁,1-Thread绑定了LockB锁!
当0-Thread要去绑定LockB锁时 和 1-Thread要去绑定LockA锁时都不能绑定,此时两个线程不能继续进行!
*/
class Ticket implements Runnable{
public boolean flag;
Ticket(boolean flag){
this.flag = flag;
}
Ticket(){
flag=true;
}
public void run(){
if(flag){
<span style="color: #ff0000;"> synchronized(MyLock.lockA){</span>
System.out.println(Thread.currentThread().getName() + " lockA &&--->lockB");
try{
Thread.sleep(100);
}catch(InterruptedException e){
}
<span style="color: #ff0000;"> synchronized(MyLock.lockB){</span>
System.out.println(Thread.currentThread().getName() + " lockB");
}
}
}
else{
<span style="color: #008000;"> synchronized(MyLock.lockB){</span>
System.out.println(Thread.currentThread().getName() + " lockB &&--->lockA");
<span style="color: #008000;"> synchronized(MyLock.lockA){</span>
System.out.println(Thread.currentThread().getName() + " lockA");
}
}
}
}
}
class MyLock{
public static final MyLock lockA = new MyLock();
public static final MyLock lockB = new MyLock();
}
public class DeadLockDemo{
public static void main(String[] args){
//虽然new了两个任务对象,但是不影响演示由于同步嵌套引起的死锁情况
// new Thread(new Ticket(true)).start();
// new Thread(new Ticket(false)).start();
///////////////////////////////////////////////////////////
Ticket tt = new Ticket();//只产生一个线程任务!这样写还要控制好sleep的时间才好.....
new Thread(tt).start();
try{
Thread.sleep(20);
}catch(InterruptedException e){
}
tt.flag=false;
new Thread(tt).start();
}
}