Java中線程死結問題

來源:互聯網
上載者:User

標籤:pack   rgs   sys   四種   產生   環路   dos   rri   使用   

我們在使用Thread時,在使用線程同步時可能會出現死結,而死結產生的原因是:

例:

兩個類中各有兩個方法,而這四種發放同步,比如顧客與服務員解決“先付款還是後付款”的問題時,就會產生死結。

死結產生的條件:

互斥條件

請求保持條件

不可剝奪條件

環路等待

死結的原因:

資源競爭和進程順序推進不當

代碼:

 1 package ThreadDemo; 2  3 //在一個同步方法中調用另一個對象的同步方法,可能產生死結 4 //死結 5 public class ThreadDemo7 { 6     public static void main(String[] args) { 7         new DeadThread(); 8     } 9 }10 11 class DeadThread implements Runnable{12     Customer c = new Customer();13     Waiter w = new Waiter();14     public DeadThread(){15         new Thread(this).start();16         w.say(c);17     }18     @Override19     public void run() {20         // TODO Auto-generated method stub21         c.say(w);22     }23 }24 25 //顧客26 class     Customer{27     public synchronized void say(Waiter w){28         System.out.println("顧客說:先吃飯再買單");29         w.doService();30     }31     public synchronized void doService(){32         System.out.println("買完單再吃飯");33     }34 }35 class Waiter{36     public synchronized void say(Customer c){37         System.out.println("服務員說:先買單再吃飯");38         c.doService();39     }40     public synchronized void doService(){41         System.out.println("吃完飯再買單");42     }43 }

 

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.