SummerVocation_Learning--java的線程死結

來源:互聯網
上載者:User

標籤:div   sys   lock   print   style   syn   tac   try   deadlock   

 1   2 public class Test_DeadLock implements Runnable { 3   4     public int flag = 1; 5     static Object o1 = new Object(),o2 = new Object(); 6     public void run() { 7         System.out.println("flag= " + flag); 8         if (flag == 1) { 9             synchronized (o1) {  //o1鎖定10                 try {11                     Thread.sleep(500);12                 } catch (Exception e) {13                     e.printStackTrace();14                 }15             synchronized (o2) { //只要再鎖定o2,就能列印出1.16                 System.out.println("1"); //但是o2被另一個線程鎖定了,所以列印不出1.17                 }18             }19         }20         if (flag == 0) {21             synchronized (o2) { //鎖定o222                 try {23                     Thread.sleep(500);24                 } catch (Exception e) {25                     e.printStackTrace();26                 }27             synchronized (o1) {  //只要再等待鎖定o1,就能列印出0.28                     System.out.println("0"); //但是o1另一個線程鎖定,無法執行。兩個線程被鎖死,誰都無法完成執行。29                 }30             }31         }32     }33     34     public static void main(String[] args) {35         Test_DeadLock t1 = new Test_DeadLock();36         Test_DeadLock t2 = new Test_DeadLock();37         t1.flag = 1;38         t2.flag = 0;39         Thread t11 = new Thread(t1);40         Thread t21 = new Thread(t2);41         t11.start(); t21.start();42  43     }44     /*45      * flag= 146        flag= 047                 兩個線程產生死結,synchronized的輸出語句未被執行。48      */49  50 }

 

SummerVocation_Learning--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.