多執行緒之死鎖
阿新 • • 發佈:2018-11-07
* 死鎖:常見情景之一:同步的巢狀 * @author 羅摩銜那 * */ class Ticketeds implements Runnable { private int num=100; Object obj=new Object(); boolean flag=true; public void run() { if(flag) while(true) { ① synchronized (obj)//同步程式碼塊,隨意物件鎖 { show(); } }else while(true) this.show(); } ②public synchronized void show()//函式程式碼塊,this { ③synchronized(obj) { if(num>0) { try {Thread.sleep(10);}catch(InterruptedException e) {} System.out.println(Thread.currentThread().getName()+"...function..."+num--); } } } public class Deadlock { public static void main(String[] args) { Ticketeds t=new Ticketeds(); Thread t1=new Thread(t); Thread t2=new Thread(t); t1.start(); try{Thread.sleep(10);}catch(InterruptedException e) {} t.flag=false; t2.start(); } }
假設執行緒0依次進入①、②、③,此時執行緒1依次進入①、②時,執行緒0想出來,而執行緒1想進去,就會出現死鎖現象.
class Tested implements Runnable { private boolean flag; Tested(boolean flag)//寫一個有參構造控制布林值 { this.flag=flag; } public void run() { if(flag) { ①synchronized(MyLock.locka) { System.out.println("if locka..."); ②synchronized(MyLock.lockb) { System.out.println("if lockb..."); } } } else { ③synchronized(MyLock.lockb) { System.out.println("else lockb..."); ④synchronized(MyLock.locka) { System.out.println("else locka..."); } } } } } class MyLock { public static final Object locka=new Object(); public static final Object lockb=new Object(); } public class DeadlockTest { public static void main(String[] args) { Tested a=new Tested(true);//建立了兩個不同的物件那麼就是兩個獨立的任務 Tested b=new Tested(false);//賦予不同的布林值-->執行路線true-if/flase-else Thread t1=new Thread(a); Thread t2=new Thread(b); t1.start(); t2.start(); } }
當執行緒0拿到了locka物件,執行緒1拿到了lockb物件,出現了死鎖