Java---16---多線程---死結,java---16---多線程
死結:
概念:
所謂死結: 是指兩個或兩個以上的進程在執行過程中,因爭奪資源而造成的一種互相等待的現象,若無外力作用,它們都將無法推進下去。此時稱系統處於死結狀態或系統產生了死結,這些永遠在互相等待的進程稱為死結進程。 由於資源佔用是互斥的,當某個進程提出申請資源後,使得有關進程在無外力協助下,永遠分配不到必需的資源而無法繼續運行,這就產生了一種特殊現象:死結。
死結發生的條件:
1.互斥條件:一個資源每次只能被一個線程使用
2.不可搶佔條件(不剝奪條件):當前進程鎖獲得的資源,在未結束前,不能強行剝奪
3.佔有且申請條件(請求與保持條件):一個進程已擁有一定的資源,又想申請別的資源,但對自己的資源又不放棄
4.迴圈條件:若干進程之間形成一種頭尾相接的迴圈等待資源的關係
一般什麼時候出現? 同步中嵌套同步
造一個死結出來:
class Test2 implements Runnable{ private boolean flag; Test2(boolean flag ) { this.flag = flag; } @Override public void run() { // TODO Auto-generated method stub if (flag) { synchronized (MyLock.locka) { System.out.println(Thread.currentThread().getName()+" if locka"); synchronized (MyLock.lockb) { System.out.println(Thread.currentThread().getName()+" if lockb"); } } } else { synchronized (MyLock.lockb) { System.out.println(Thread.currentThread().getName()+" else lockb"); synchronized (MyLock.locka) { System.out.println(Thread.currentThread().getName()+" else locka"); } } } }}class MyLock{ static Object locka = new Object(); static Object lockb = new Object();}public class DieLockTest{ public static void main(String[] args) { Thread t1 = new Thread(new Test2(true)); Thread t2 = new Thread(new Test2(false)); t1.start(); t2.start(); }}
將之前驗證同步函數的鎖是this的程式也弄成死結:
class Test1 implements Runnable{ private static int num = 500; Object obj = new Object(); boolean flag = true; public void run () { if (flag) { while (true) { synchronized (obj)//鎖是obj { show ();//鎖是this } } } else { while (true) { show(); } } } public synchronized void show ()// 鎖是 this { synchronized (obj)//鎖是 obj { if (num >= 0) { try { Thread.sleep(20); } catch (Exception e) { // TODO: handle exception System.out.println(e.toString()); } System.out.println(Thread.currentThread().getName()+">>--code-- "+num--); } } }}public class DieLock{ public static void main (String[] args) { Test1 t = new Test1(); Thread a = new Thread(t); Thread b = new Thread(t); a.start(); try { Thread.sleep(20); } catch (Exception e) { // TODO: handle exception } t.flag = false; b.start(); }}
死結的預防:
死結的預防是保證系統不進入死結狀態的一種策略。
知道了死結發生的條件,要避免死結就要從打破條件入手。
點擊開啟連結