java的死結學習

來源:互聯網
上載者:User

標籤:alt   post   技術分享   dea   pac   version   ext   code   lock   

學習java的死結寫的代碼

也是看書上的然後自己敲了一個

<span style="font-size:18px;">package synchronization.java.test;/** * 關於java中線程死結範例 * 在學習作業系統的時候有線程死結可是也僅僅是理解也沒有親自己主動手敲過 * 如今學java既然學到這裡了就敲了一個簡單的以進餐為例的代碼 * @author hello * @version 8 */public class DeadLock {     static String knife="餐刀",fork="叉子";       static class A extends Thread{     public void run(){  //重寫的方法     synchronized(knife){//     System.out.println("小明拿到了"+knife+"等待"+fork+".........");     try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}     synchronized(fork){//這是用來測試的其實因為死結了這一步永遠也不會出現     System.out.println("小明又拿到"+fork);     }     }     }     }     static class B extends Thread{     public void run(){     synchronized(fork){     System.out.println("小華拿到了"+fork+"等待"+knife+".........");     try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}     synchronized(knife){//這是用來測試的其實因為死結了這一步永遠也不會出現     System.out.println("小華又拿到"+knife);    }     }     }     }     static class Demo extends  Thread{     public Demo(){     this.setDaemon(true);     }     public void run(){     while(true){     try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}//這個線程一直在執行     System.out.println("程式正在執行中......");     }     }          }public static void main(String[] args) {     new A().start();//因為是靜態直接new即可     new B().start();     new Demo().start();}}</span>

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" >

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.