Java的死結的例子

來源:互聯網
上載者:User

標籤:java   死結   例子   

代碼:

/* * DESCRIPTION :  * USER : zhouhui * DATE : 2017/8/2 10:12 */public class DeadLockDemo {    public static void main(String[] args) {        //分別定義兩個被鎖的對象        Entity entity1 = new Entity("entity1");        Entity entity2 = new Entity("entity2");        //定義兩個線程,並設定不同的名字        new Thread(new MyR(entity1,entity2),"Thread 1").start();        new Thread(new MyR(entity2,entity1),"Thread 2").start();    }}class MyR implements Runnable{    private Entity entity1;    private Entity entity2;    public MyR(Entity entity1,Entity entity2){        this.entity1 = entity1;        this.entity2 = entity2;    }    public void run() {        System.out.println(Thread.currentThread().getName() + "嘗試獲得"+entity1.getName()+"的鎖");        synchronized (entity1){//嘗試獲得第一個鎖            System.out.println(Thread.currentThread().getName() + "獲得"+entity1.getName()+"的鎖");            try {                Thread.sleep(1000);            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println(Thread.currentThread().getName() + "嘗試獲得"+entity2.getName()+"的鎖");            synchronized (entity2){//嘗試獲得第二個鎖                System.out.println(Thread.currentThread().getName() + "獲得"+entity2.getName()+"的鎖");                try {                    Thread.sleep(1000);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }    }}/** * 定義一個鎖的對象,為了方便區分定義一個name區分對象 */class Entity{    private String name;    public Entity(String name) {        this.name = name;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}

列印結果:

Thread 1嘗試獲得entity1的鎖Thread 2嘗試獲得entity2的鎖Thread 1獲得entity1的鎖Thread 2獲得entity2的鎖Thread 2嘗試獲得entity1的鎖Thread 1嘗試獲得entity2的鎖


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.