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,造成死锁。

转载于:https://www.cnblogs.com/uptothesky/p/8410860.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值