死鎖及解決方案

死鎖:t1線程和t2線程各自佔有共享資源o1,o2,互相在等待對方釋放資源,這樣造成的兩個線程互相等待,沒法繼續運行的"死鎖"狀態.
解決方案:同一個代碼塊,不能持有兩個對象鎖.ide

package DeadLock;

public class DeadLockUse {
public static void main(String[] args) {
    Object o1 = new Object();
    Object o2 = new Object();
    Thread t1 = new MyThread1(o1,o2);
    Thread t2 = new MyThread2(o1,o2);
    t1.start();
    t2.start();
}
}
class MyThread1 extends Thread{
    Object o1;
    Object o2;
    public MyThread1(Object o1, Object o2) {
        this.o1 = o1;
        this.o2 = o2;
    }
    public void run() {
        synchronized(o1) {
            try {
                Thread.sleep(1000*3);
            } catch (InterruptedException e) {
                // TODO 自動生成的 catch 塊
                e.printStackTrace();
            }
            synchronized(o2) {
                    System.out.println("死鎖解決了1!");
            }
        }
    }
}
class MyThread2 extends Thread{
    Object o1;
    Object o2;
    public MyThread2(Object o1, Object o2) {
        this.o1 = o1;
        this.o2 = o2;
    }
    public void run() {
        synchronized(o2) {
            try {
                Thread.sleep(3*1000);
            } catch (InterruptedException e) {
                // TODO 自動生成的 catch 塊
                e.printStackTrace();
            }
            synchronized(o1) {
                System.out.println("死鎖解決了2!");
            }
        }
    }
}

解決方法:this

package DeadLock;

public class DeadLockUse {
public static void main(String[] args) {
    Object o1 = new Object();
    Object o2 = new Object();
    Thread t1 = new MyThread1(o1,o2);
    Thread t2 = new MyThread2(o1,o2);
    t1.start();
    t2.start();
}
}
class MyThread1 extends Thread{
    Object o1;
    Object o2;
    public MyThread1(Object o1, Object o2) {
        this.o1 = o1;
        this.o2 = o2;
    }
    public void run() {
        synchronized(o1) {
            try {
                Thread.sleep(1000*3);
            } catch (InterruptedException e) {
                // TODO 自動生成的 catch 塊
                e.printStackTrace();
            }
        }
        synchronized(o2) {
            System.out.println("死鎖解決了1!");
    }
    }
}
class MyThread2 extends Thread{
    Object o1;
    Object o2;
    public MyThread2(Object o1, Object o2) {
        this.o1 = o1;
        this.o2 = o2;
    }
    public void run() {
        synchronized(o2) {
            try {
                Thread.sleep(3*1000);
            } catch (InterruptedException e) {
                // TODO 自動生成的 catch 塊
                e.printStackTrace();
            }
        }
        synchronized(o1) {
            System.out.println("死鎖解決了2!");
        }
    }
}

運行結果
死鎖及解決方案線程

相關文章
相關標籤/搜索