java 多線程死結

來源:互聯網
上載者:User

標籤:style   相等   tar   int   zed   username   exce   AC   span   

死結案例:

package com.test;public class DealThread implements Runnable {        public String username;    public Object lock1 = new Object();    public Object lock2 = new Object();        public void setFlag(String username) {        this.username = username;    }        @Override    public void run() {        if (username.equals("a")) {            synchronized (lock1) {                try {                    System.out.println("username = " + username);                    Thread.sleep(3000);                } catch (Exception e) {                    e.printStackTrace();                }                synchronized (lock2) {                    System.out.println("按 lock1 -> lock2 代碼順序執行了");                }            }        }        if (username.equals("b")) {            synchronized (lock2) {                try {                    System.out.println("username = " + username);                    Thread.sleep(3000);                } catch (Exception e) {                    e.printStackTrace();                }                synchronized (lock1) {                    System.out.println("按 lock2 -> lock1 代碼順序執行了");                }            }        }    }}
package com.test;public class Run {        public static void main(String[] args) {                try {            DealThread d1 = new DealThread();            d1.setFlag("a");            Thread thread1 = new Thread(d1);            thread1.start();            Thread.sleep(100);            d1.setFlag("b");            Thread thread2 = new Thread(d1);            thread2.start();        } catch (Exception e) {            e.printStackTrace();        }    }}
運行結果:username = ausername = b

死結是程式設計的Bug,在設計程式時就要避免雙方互相持有對方鎖的情況。本案例使用synchronized嵌套的代碼結構來實現死結,其實不適用嵌套的代碼結構也會出現死結。 只要互相等待對方釋放鎖就有可能出現死結。

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.