3. ReentrantLock-可重入锁

2020-08-12  本文已影响0人  说书的苏斯哈

相比较synchronized而言 ReentrantLock有以下特点:

基本语法

首先需要创建一个ReentrantLock对象,以及获取锁,在try里面执行临界区代码,在finally里面释放锁,值得注意的是lock和unlock一定要成对出现

  ReentrantLock reentrantLock = new ReentrantLock();
        reentrantLock.lock();//获取锁
        try{
            //临界区
        }finally {
            reentrantLock.unlock();
        }

可重入

同synchronized一样,ReentrantLock是支持重入的如下所示

 static ReentrantLock reentrantLock = new ReentrantLock();
    public static void main(String[] args) {
        reentrantLock.lock();//获取锁
        try{
          log.debug("访问到Main的ReentrantLock的临界区");
          method();
        }finally {
            reentrantLock.unlock();
        }
    }
    public static void method(){
        reentrantLock.lock();//获取锁
        try{
            log.debug("访问到method的ReentrantLock的临界区");
        }finally {
            reentrantLock.unlock();
        }
    }

可打断

   static ReentrantLock reentrantLock = new ReentrantLock();
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    log.debug("尝试获取锁");
                    reentrantLock.lockInterruptibly();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    log.debug("被打断了");
                    return;
                }
                log.debug("打断了之后还能接着执行么");

                try{
                    log.debug("获取到锁");
                }finally {
                        reentrantLock.unlock();
                }
            }
        },"t1");
        reentrantLock.lock(); //主线程先获取锁
        t1.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t1.interrupt();
    }

锁超时

公平锁

条件变量

上一篇 下一篇

猜你喜欢

热点阅读