/*目的:自己寫一個由于同步嵌套引起的死鎖!思路:多個線程在執行時,某一時刻,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){ synchronized(MyLock.lockA){System.out.println(Thread.currentThread().getName() + " lockA &&--->lockB");try{Thread.sleep(100);}catch(InterruptedException e){} synchronized(MyLock.lockB){System.out.println(Thread.currentThread().getName() + " lockB");}}}else{ synchronized(MyLock.lockB){System.out.println(Thread.currentThread().getName() + " lockB &&--->lockA"); synchronized(MyLock.lockA){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();}
}