Java 死锁优化

死锁示例1

public class SyncThread implements Runnable{
    private Object obj1;
    private Object obj2;

    public SyncThread(Object obj1, Object obj2) {
        this.obj1 = obj1;
        this.obj2 = obj2;
    }

    @Override
    public void run() {
        String name=Thread.currentThread().getName();
        System.out.println(name+" acquiring lock on "+obj1);
        synchronized (obj1){
            System.out.println(name+" acquired lock on "+obj1);
            work();
            System.out.println(name+" acquiring lock on "+obj2);
            synchronized (obj2){
                System.out.println(name+" acquired lock on "+obj2);
                work();
            }
            System.out.println(name+" released lock on "+obj2);
        }
        System.out.println(name+" released lock on "+obj1);
        System.out.println(name+" finished execution.");

    }
    void work(){
        try {
            Thread.sleep(30000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}
View Code

调用代码

public class ThreadDeadLock {
    public static void main(String[] args) throws InterruptedException {
        Object obj1=new Object();
        Object obj2=new Object();
        Object obj3=new Object();
        Thread t1=new Thread(new SyncThread(obj1,obj2),"t1");
        Thread t2=new Thread(new SyncThread(obj2,obj3),"t2");
        Thread t3=new Thread(new SyncThread(obj3,obj1),"t3");
        t1.start();
        Thread.sleep(5000);
        t2.start();
        Thread.sleep(5000);
        t3.start();
    }


}
View Code

这里obj1等待obj2,obj2等待obj3,obj3等待obj1,造成死锁。

posted @ 2018-02-03 21:49  uptothesky  阅读(133)  评论(0编辑  收藏  举报