Java線程死結

來源:互聯網
上載者:User

標籤:war   一個   ace   public   bsp   對象   thread   問題   warnings   

 Java多線程使用synchronized 鎖時,可能會出現死結;死結會導致兩個線程無限等待,致使程式異常。因此使用synchronized 關鍵字時注意死結的問題。

 

筆者在第一次運行程式的時候屬性 A=“a”、B=“a”,並沒有引起死結的問題;原因很簡單,這時A 和 B的地址是一樣的,synchronized 認為是同一個對象資源,不會對對象A 和 B同時加鎖。

 

引起死結的例子: 

public class DeadLock {

 private String A = "a"; private String B = "b";@SuppressWarnings("static-access")public void deadLock(){Thread thread1 = new Thread(new Runnable(){@Overridepublic void run() {System.out.println("thread1-start");synchronized (A) {System.out.println("1" + A);try {Thread.currentThread().sleep(2000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}synchronized (B){System.out.println("2" + B);}}System.out.println("thread1-end");}});Thread thread2 = new Thread(new Runnable(){@Overridepublic void run() {System.out.println("thread2-start");synchronized (B) {System.out.println("3" + B);synchronized (A){System.out.println("4" + A);}}System.out.println("thread2-end");}});thread1.start();thread2.start();}public static void main(String[] args){     new DeadLock().deadLock();}}

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.