Java简单锁机制,synchronized死锁并解决

下面例子有一定概率deadLock

import com.sun.org.apache.regexp.internal.RE;

/**
 * Created by butter on 16/11/15.
 */

class Resource{
    private String name;
    private int resource;

    public Resource(String name, int resource) {
        this.name = name;
        this.resource = resource;
    }
    synchronized void doSome(){
        System.out.println("doing some thing");
        resource++;
    }
    synchronized void cooperate(Resource resource){
        System.out.println("cooperating");
        resource.doSome();
    }
}


/**
 *
 * 两个Resource对象 r1, r2
 * 两个线程t1, t2
 * t1调用cooperate(r2)时获取r1的锁,如果此时此刻t2正在调用cooperate(r1)将获取r2的锁
 * 这时,t1.cooperate(r2)执行r2.doSome(),将申请获取r2的锁,r2锁被t2获取,所以等待
 * 并且,t2.cooperate(r1)执行r1.doSome(),将申请获取r1的锁,r1的锁被t1获取,继续等待,
 *
 * 结果就是t1 等 t2 的锁  t2 等 t1 的锁,互相等待对方的锁,造成死锁
 */

public class Demo_deadLock {
    public static void main(String[] args) {
        Resource r1 = new Resource("1", 1);
        Resource r2 = new Resource("2", 2);

//      循环次数多一些,为了得到上述情况
        Thread thread1 = new Thread(()->{
            for (int i = 0; i < 100; i++) {
                r1.doSome();
                r1.cooperate(r2);
            }

        });
        System.out.println("t1 over");
        Thread thread2 = new Thread(()->{
            for (int i = 0; i < 100; i++) {
                r2.doSome();
                r2.cooperate(r1);
            }

        });
        thread1.start();
        thread2.start();
        System.out.println("t2 over");

    }
}

解决方案:

import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by butter on 16-11-17.
 */
/**
 * 
 * 每次线程尝试获取lock,获取不到,释放已有lock,解决deadlock
 * 
 */


class Resource1{

    private String name;
    private int resource;
    private ReentrantLock lock = new ReentrantLock(); //Lock接口

    public Resource1(String name, int resource) {
        this.name = name;
        this.resource = resource;
    }
    void doSome(){

        System.out.println(Thread.currentThread().getName() + " doing some thing: " + name+ " " + resource);
        resource++;
    }
    void cooperate(Resource1 resource){
        while(true) {
            try {
                if (lockMeAnd(resource)) {
                    System.out.println(Thread.currentThread().getName() + "  r1 & r2 has been Locked");
                    System.out.println(Thread.currentThread().getName() + " cooperating");
                    resource.doSome();
                    break;
                } else {
                    System.out.println( Thread.currentThread().getName() +"       can't lock r1&r2");
                }
            }finally {
                unLockMeAnd(resource);
                System.out.println(Thread.currentThread().getName() + " r1 & r2 has been unLocked");
            }

        }
    }

    private boolean lockMeAnd(Resource1 res){
        /*尝试获取锁, 获取不到->不阻塞*/
        return this.lock.tryLock() && res.lock.tryLock();
    }
    private void unLockMeAnd(Resource1 res){
        if(this.lock.isHeldByCurrentThread()){
            this.lock.unlock();
        }
        if(res.lock.isHeldByCurrentThread()){
            res.lock.unlock();
        }
    }
}


public class Demo_noDeadLock {
    public static void main(String[] args) {
        Resource1 r1 = new Resource1("a", 1);
        Resource1 r2 = new Resource1("b", 2);

        Thread t1 = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                r1.cooperate(r2);
            }
        });
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                r2.cooperate(r1);
            }
        });
        t1.start();
        t2.start();
    }
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值