關於死結,並用Java實現一個死結

來源:互聯網
上載者:User

標籤:

產生死結的原因主要是:
(1) 因為系統資源不足。
(2) 進程運行推進的順序不合適。
(3) 資源分派不當等。
如果系統資源充足,進程的資源請求都能夠得到滿足,死結出現的可能性就很低,否則
就會因爭奪有限的資源而陷入死結。其次,進程運行推進順序與速度不同,也可能產生死結。
產生死結的四個必要條件:
(1) 互斥條件:一個資源每次只能被一個進程使用。
(2) 請求與保持條件:一個進程因請求資源而阻塞時,對已獲得的資源保持不放。
(3) 不剝奪條件:進程已獲得的資源,在末使用完之前,不能強行剝奪。
(4) 迴圈等待條件:若干進程之間形成一種頭尾相接的迴圈等待資源關係。
這四個條件是死結的必要條件,只要系統發生死結,這些條件必然成立,而只要上述條件之
一不滿足,就不會發生死結。
死結的解除與預防:
理解了死結的原因,尤其是產生死結的四個必要條件,就可以最大可能地避免、預防和
解除死結。所以,在系統設計、進程調度等方面注意如何不讓這四個必要條件成立,如何確
定資源的合理分配演算法,避免進程永久佔據系統資源。此外,也要防止進程在處於等待狀態
的情況下佔用資源。因此,對資源的分配要給予合理的規劃。
下面就用Java來故意實現一個死結,這也是常見面試題之一:

package 死結;class A{    synchronized void funA(B b){        String name = Thread.currentThread().getName();        System.out.println(name+"進入A.foo");        /*try {            Thread.sleep(2000);        } catch (InterruptedException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }*/        System.out.println(name+"調用B類的last方法");        b.last();    }    synchronized void last()    {        System.out.println("A的last方法");    }}class B{    synchronized void funB(A a){        String name = Thread.currentThread().getName();        System.out.println(name+"進入B.foo");        try {            Thread.sleep(2000);        } catch (InterruptedException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        System.out.println(name+"調用A類的last方法");        a.last();    }    synchronized void last()    {        System.out.println("B的last方法");    }}public class DeadLockDemo implements Runnable{    A a=new A();    B b=new B();    public DeadLockDemo() {        // TODO Auto-generated constructor stub        new Thread(this).start();        a.funA(b);    }    public void run(){        b.funB(a);    }    public static void main(String []args)    {            new DeadLockDemo();    }}

關於死結,並用Java實現一個死結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.