Java ReentrantLock 详解_reentrantlock.trylock(5, timeunit.seconds)-程序员宅基地

技术标签: java  Android  

ReentrantLock 和 synchronized 的区别:

1.ReentrantLock 不需要代码块,在开始的时候lock,在结束的时候unlock 就可以了。

但是要注意,lock 是有次数的,如果连续调用了两次lock,那么就需要调用两次unlock。否则的话,别的线程是拿不到锁的。

    /**
     * 很平常的用锁 没有感觉reentrantlocak 的强大
     *
     * 如果当前线程已经拿到一个锁了 那么再次调用 会里面返回true
     * 当前线程的锁数量是 2个
     *
    */
    private void normalUse() {
        ReentrantLock reentrantLock =  new ReentrantLock();
        new Thread("thread1"){
            @Override
            public void run() {
                super.run();
                LogToFile.log(TAG,"thread1 lock");
                reentrantLock.lock();
                reentrantLock.lock();
               
                LogToFile.log(TAG,"thread1 getHoldCount:"  + reentrantLock.getHoldCount() );

                try {
                    LogToFile.log(TAG,"thread1 run");

                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                 //如果说你的线程占了两个锁 一个没有释放 其他线程都拿不到这个锁
                 //上面lock 了两次 这里需要unLock 两次
                reentrantLock.unlock();
                reentrantLock.unlock();
                LogToFile.log(TAG,"thread1 unlock");
            }
        }.start();


        new Thread("thread2"){
            @Override
            public void run() {
                super.run();

                LogToFile.log(TAG,"thread2 lock");
                reentrantLock.lock();
                LogToFile.log(TAG,"thread2 run");

                reentrantLock.unlock();
                LogToFile.log(TAG,"thread2 unlock");

            }
        }.start();
    }

ReentrantLock trylock()

ReentrantLock trylock 会尝试去拿锁,如果拿得到,就返回true, 如果拿不到就返回false.这个都是立马返回,不会阻塞线程。
如果当前线程已经拿到锁了,那么trylock 会返回true.

    /**
     * trylock 不管能不能拿到锁 都会里面返回结果 而不是等待
     * tryLock 会破坏ReentrantLock 的 公平机制
     * 注意 如果没有拿到锁 执行完代码之后不要释放锁,
     * 否则会有exception
     *
     */
    private void UseTryLock() {
        ReentrantLock reentrantLock =  new ReentrantLock();
        new Thread("thread1"){
            @Override
            public void run() {
                super.run();
                LogToFile.log(TAG,"thread1 lock");
                reentrantLock.lock();
                try {
                    LogToFile.log(TAG,"thread1 run");

                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                reentrantLock.unlock();
                LogToFile.log(TAG,"thread1 unlock");
            }
        }.start();


        new Thread("thread2"){
            @Override
            public void run() {
                super.run();

                LogToFile.log(TAG,"thread2 tryLock");
                boolean success = reentrantLock.tryLock();
                LogToFile.log(TAG,"thread2 run");

                if (success) {
                    reentrantLock.unlock();
                    LogToFile.log(TAG,"thread2 unlock");
                    //    java.lang.IllegalMonitorStateException
                    //        at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:123)
                    //        at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1235)
                    //        at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:429)

                }

            }
        }.start();
    }

ReentrantLock .tryLock(5, TimeUnit.SECONDS)

ReentrantLock 可以指定,尝试去获取锁,等待多长时间之后,如果还获取不到,那么就放弃。

    /**
     * tryLock(5, TimeUnit.SECONDS)
     * 如果5s之后 还拿不到锁  那么就不再堵塞线程,也不去拿锁了 执行执行下面的代码了
     */
    private void UseTryLockWhitTime() {
        ReentrantLock reentrantLock =  new ReentrantLock();
        new Thread("thread1"){
            @Override
            public void run() {
                super.run();
                LogToFile.log(TAG,"thread1 lock");
                reentrantLock.lock();
                try {
                    LogToFile.log(TAG,"thread1 run");

                    Thread.sleep(1000 * 10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                reentrantLock.unlock();
                LogToFile.log(TAG,"thread1 unlock");
            }
        }.start();


        new Thread("thread2"){
            @Override
            public void run() {
                super.run();

                LogToFile.log(TAG,"thread2 tryLock");
                boolean success = false;
                try {
                    success = reentrantLock.tryLock(5, TimeUnit.SECONDS);
                    LogToFile.log(TAG,"thread2 run");

                    if (success) {
                        reentrantLock.unlock();
                        LogToFile.log(TAG,"thread2 unlock");
                        //    java.lang.IllegalMonitorStateException
                        //        at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:123)
                        //        at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1235)
                        //        at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:429)

                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

ReentrantLock .lock();

一旦调用了ReentrantLock .lock() ,如果你的线程被其他线程interrupt,那么你的线程并不会interrupt,而是继续等待锁。

    /**
     * lockInterruptibly() 和  lock 的区别是
     * 如果当前线程被Interrupt 了,那么lockInterruptibly 就不再等待锁了。直接会抛出来一个异常给你处理
     * 如果是lock 的话 就算 线程被其他的线程lockInterrupt 了,不管用,他还会继续等待锁
     */
    private void UseLockIntercepter() {
        ReentrantLock reentrantLock =  new ReentrantLock();
        Thread thread = new Thread("thread1") {
            @Override
            public void run() {
                super.run();
                LogToFile.log(TAG, "thread1 lock");
                reentrantLock.lock();
                LogToFile.log(TAG, "thread1 run");
                if (reentrantLock.getHoldCount() != 0) {
                    reentrantLock.unlock();
                }
                LogToFile.log(TAG, "thread1 unlock");
            }
        };


        new Thread("thread2"){
            @Override
            public void run() {
                super.run();

                LogToFile.log(TAG,"thread2 tryLock");
                boolean success = false;
                try {
                    reentrantLock.lock();
                    thread.start();

                    thread.interrupt();
                    success = reentrantLock.tryLock(5, TimeUnit.SECONDS);
                    LogToFile.log(TAG,"thread2 run");

                    if (success) {
                        reentrantLock.unlock();
                        reentrantLock.unlock();
                        LogToFile.log(TAG,"thread2 unlock");
                        //    java.lang.IllegalMonitorStateException
                        //        at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:123)
                        //        at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1235)
                        //        at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:429)

                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

ReentrantLock .lockInterruptibly();

如果当前线程调用lockInterruptibly 这个方法去获取锁,当其他的线程把你的线程给interrupt 之后,那么你的线程就不再等待锁了,执行下面的代码。

    /**
     * lockInterruptibly() 和  lock 的区别是
     * 如果当前线程被Interrupt 了,那么lockInterruptibly 就不再等待锁了。直接会抛出来一个异常给你处理
     * 如果是lock 的话 就算 线程被其他的线程lockInterrupt 了,不管用,他还会继续等待锁
     */
    private void UseLockIntercepter2() {
        ReentrantLock reentrantLock =  new ReentrantLock();
        Thread thread = new Thread("thread1") {
            @Override
            public void run() {
                super.run();
                LogToFile.log(TAG, "thread1 lock");
                try {
                    reentrantLock.lockInterruptibly();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    LogToFile.log(TAG, "thread1 lock InterruptedException ");

                }
                LogToFile.log(TAG, "thread1 run");
                if (reentrantLock.getHoldCount() != 0) {
                    reentrantLock.unlock();
                }
                LogToFile.log(TAG, "thread1 unlock");
            }
        };


        new Thread("thread2"){
            @Override
            public void run() {
                super.run();

                LogToFile.log(TAG,"thread2 tryLock");
                boolean success = false;
                try {
                    reentrantLock.lock();
                    thread.start();

                    thread.interrupt();
                    success = reentrantLock.tryLock(5, TimeUnit.SECONDS);
                    LogToFile.log(TAG,"thread2 run");

                    if (success) {
                        reentrantLock.unlock();
                        reentrantLock.unlock();
                        LogToFile.log(TAG,"thread2 unlock");
                        //    java.lang.IllegalMonitorStateException
                        //        at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:123)
                        //        at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1235)
                        //        at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:429)

                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

ReentrantLock newCondition()使用:

condition. 的await 相当于 object 的wait 方法,就是等待其他线程唤醒,但是调用之前必须要reentrantLock.lock(); 一下,不然会抛异常。

    /**
     * tryLock(5, TimeUnit.SECONDS)
     * 如果5s之后 还拿不到锁  那么就不再堵塞线程,也不去拿锁了 执行执行下面的代码了
     */
    private void UseCondition() {
        ReentrantLock reentrantLock =  new ReentrantLock();
        Condition condition = reentrantLock.newCondition();
        Thread thread = new Thread("thread1") {
            @Override
            public void run() {
                super.run();

                try {
                    reentrantLock.lock();
                    LogToFile.log(TAG, "thread1 wait");
                    //await 其实是会释放锁的 其他的线程可以拿到锁 然后signal  不然的话岂不是要卡死?
                    condition.await();

                    LogToFile.log(TAG, "thread1 run");

                    Thread.sleep(1000 * 3);
                    condition.signalAll();
                    reentrantLock.unlock();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                LogToFile.log(TAG, "thread1 unlock");
            }
        };
        thread.start();


        Thread thread1 = new Thread("thread2") {
            @Override
            public void run() {
                super.run();
                //调用signal 之前一定要lock
                reentrantLock.lock();
                //就算没有人调用await 那么signal 方法也不会有什么问题
                condition.signal();

                try {
                    LogToFile.log(TAG, "thread2 wait");
                    condition.await();
                    LogToFile.log(TAG, "thread2 run");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                reentrantLock.unlock();
            }
        };
        thread1.start();
    }

Object wait方法使用:

wait 方法调用之前也要synchronized 一个锁。

    /**
     * 使用wait
     */
    private void UseWait() {
        ReentrantLock reentrantLock =  new ReentrantLock();
        Condition condition = reentrantLock.newCondition();
        new Thread("thread1"){
            @Override
            public void run() {
                super.run();

                try {
                    synchronized (condition) {
                        LogToFile.log(TAG,"thread1 wait");
                        condition.wait();
                    }

                    LogToFile.log(TAG,"thread1 run");

                    Thread.sleep(1000 * 10);
                    synchronized (condition) {
                        condition.notifyAll();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                LogToFile.log(TAG,"thread1 unlock");
            }
        }.start();


        new Thread("thread2"){
            @Override
            public void run() {
                super.run();
                synchronized (condition) {
                    condition.notify();

                }
                try {
                    LogToFile.log(TAG,"thread2 wait");
                    synchronized (condition){
                        condition.wait();
                    }
                    LogToFile.log(TAG,"thread2 run");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

synchronized

synchronized 锁等待的线程,当被其他线程interrupt 的时候,并不会停止。

/**
 * synchronized 的锁,不能被中断
 */
public void testSyncInter(){
    Object lock = new Object();
    Thread thread = new Thread("thread1") {
        @Override
        public void run() {
            super.run();
            synchronized (lock) {
                LogToFile.log(TAG, "thread1 lock");
                LogToFile.log(TAG, "thread1 run");
            }
            LogToFile.log(TAG, "thread1 unlock");

        }
    };


    new Thread("thread2"){
        @Override
        public void run() {
            super.run();
            synchronized (lock) {
                LogToFile.log(TAG,"thread2 start");
                thread.start();
                thread.interrupt();

            }
            LogToFile.log(TAG,"thread2 run");
        }
    }.start();
}

BlockingQueue 就是使用ReentrantLock 实现的阻塞队列:

    /**
     * BlockingQueue  会阻塞当前的线程  等着其他线程放数据
     */
    public void testArrayBlockQueue(){
        BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<>(4);

        new Thread("thread1"){
            @Override
            public void run() {
                super.run();
                try {
                    LogToFile.log(TAG,"thread1 take");
                    blockingQueue.take();
                    LogToFile.log(TAG,"thread1 take  get");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread("thread2"){
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    LogToFile.log(TAG,"thread2 put");

                    //put 会阻塞 但是add 不会
                    blockingQueue.put(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

ArrayBlockingQueue 源码解析:

下面的代码,可以看到ArrayBlockingQueue 创建了ReentrantLock ,以及两个condition


    /** Main lock guarding all access */
    final ReentrantLock lock;

    /** Condition for waiting takes */
    private final Condition notEmpty;

    /** Condition for waiting puts */
    private final Condition notFull;

public ArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException();
        this.items = new Object[capacity];
        lock = new ReentrantLock(fair);
        notEmpty = lock.newCondition();
        notFull =  lock.newCondition();
    }

当我们往里面放元素的时候,我们会对notFull 进行等待,因为队列不是空的了。

当出队列的时候,notFull.signal(); 也就是当前的队列不是满的了,可以放元素进去了。

    /**
     * Inserts the specified element at the tail of this queue, waiting
     * for space to become available if the queue is full.
     *
     * @throws InterruptedException {@inheritDoc}
     * @throws NullPointerException {@inheritDoc}
     */
    public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length)
                notFull.await();
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }

    private E dequeue() {
        // assert lock.getHoldCount() == 1;
        // assert items[takeIndex] != null;
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        E x = (E) items[takeIndex];
        items[takeIndex] = null;
        if (++takeIndex == items.length)
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
        notFull.signal();
        return x;
    }

当我们往里面取元素的时候,如果队列是空的了,那么notEmpty 就要等待,当enqueue一个元素的时候,notEmpty 不是空就唤醒,那么take 就可以执行去拿元素了。

    public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

    private void enqueue(E x) {
        // assert lock.getHoldCount() == 1;
        // assert items[putIndex] == null;
        final Object[] items = this.items;
        items[putIndex] = x;
        if (++putIndex == items.length)
            putIndex = 0;
        count++;
        notEmpty.signal();
    }

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u013270444/article/details/104951842

智能推荐

Winform两种方法实现打包_winform打包-程序员宅基地

文章浏览阅读353次。 一.1. 在现有项目的解决方案中添加新的项目: 右击"解决方案",选择"添加"--"新建项目", 在"添加新项目"的选择窗口中, "项目类型"选"其他项目类型"--"安装和部署","模板"选"安装项目",给新项目指定名称,位置;2. 在新添加的安装项目上右击, 选择"视图"--"文件系统", 右击"目标计算机上的文件系统"作侧的"应用程序文件夹", 选择"添加文件"或者"_winform打包

2017年深度学习语义分割导读_refinenet: multi-path refinement networks for dens-程序员宅基地

文章浏览阅读6.9k次,点赞3次,收藏15次。翻译了2017年深度学习语义分割导读,博客链接如下:http://blog.qure.ai/notes/semantic-segmentation-deep-learning-review其中介绍了从FCN开始8种有代表性的图片语义分割方法的主要贡献,简单介绍,并做了简单的评论。_refinenet: multi-path refinement networks for dense prediction

VS2015 连接、查询SqlServer/_variant_t 与 std::string 相互转换__variant_t std::string-程序员宅基地

文章浏览阅读447次。以下代码在vs2015中测试通过,使用标准Windows库。连接SqlSerer和查询的代码是东拼西凑的,_variant_t 与 std::string 相互转换是自己翻书写的。_variant_t 如果是日期、整数等其他数据类型,会自动转成std::string,没有乱码。// SqlServerTest.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <ICRSINT.H>#include <vector>#__variant_t std::string

java调用第三方dll文件-程序员宅基地

文章浏览阅读835次。网上调用第三方dll组件的方法有很多,作者是通过jna进行调用的,试过com组件封装但是组件,但是一直没有成功,因为是.net的dll文件(net.dll),故无法直接使用jna进行调用,所以作者的思路是将net.dll用c先引入后,再做成一个c的dll,供dll后改用jna调用c的dll,c的dll再调用原始的dll文件..._java调用第三方dll文件

网关神器Kong(一):介绍_kong网关-程序员宅基地

文章浏览阅读8.6k次,点赞5次,收藏36次。物联网网关神器 Kong ( 一 )当你看到这只大猩猩的时候,是不是感觉优点萌萌的。哈哈,这就是我们这篇文章要讲解的一个开源项目 – Kong( 云原生架构下的分布式API 网关 )。为什么说 Kong 是物联网网关神器?在 IOT 系统架构中,为了保证系统的鲁棒性和高可扩展性。我们需要一个强大的 API 网关来承受住遍布各地的 IOT 设备所传输的信息。插件架构设计的 Kong 使得它具有了强大的兼容性,和可扩展性。TCP 和 UDP原始流的支持,更是使得它可以适配多种协议,完美的解决了 IOT_kong网关

Element-UI 自定义upload组件(进度条,删除,下载)_el-upload自定义删除-程序员宅基地

文章浏览阅读755次。on-progress=“uploadFileProcess” //文件传输过程(处理进度条):show-file-list=“false” //自定义样式所以设置false不显示。:before-upload=“beforeUploadFile” //文件上传前。:on-success=“handleFileSuccess” //文件成功。:action=“uploadUrl” //文件上传的地址(必填):file-list=“fileArr”//文件列表。multiple//多文件上传。_el-upload自定义删除

随便推点

2017二级c语言考试大纲,2017年计算机等级考试二级C语言程序设计考试大纲-程序员宅基地

文章浏览阅读66次。摘要全国计算机等级考试二级C 语言程序设计考试大纲(2013 年版)基本要求1. 熟悉Visual C++ 6. 0 集成开发环境。2. 掌握结构化程序设计的方法,具有良好的程序设计风格。3. 掌握程序设计中简单的数据结构和算法并能阅读简单的程序。4. 在Visual C++ 6. 0 集成环境下,能够编写简单的C 程序,并具有基本的纠错和调试程序的能力。考试内容一、C 语言程序的结构1. 程序的...

支付宝的骚操作。。-程序员宅基地

文章浏览阅读227次。前天的文章刚提到大家买基金的热情一路高涨:基金韭菜们太疯狂了!然后昨天我就在支付宝上面有了几个新的发现。支付宝作为一个支付金融工具,本来就是有理财属性的,在支付宝的App上面也有一个单独...

工作流-flowable_flowable工作流-程序员宅基地

文章浏览阅读1.9k次,点赞3次,收藏15次。1. 简单介绍工作流 2. 使用flowable和java api写一个demo 3. 使用flowable集合springboot写一个demo_flowable工作流

__attribute__ 你知多少?___attribute__是哪种变量-程序员宅基地

文章浏览阅读4.9k次,点赞9次,收藏47次。GNU C 的一大特色就是__attribute__ 机制。__attribute__ 可以设置函数属性(Function Attribute )、变量属性(Variable Attribute )和类型属性(Type Attribute )。__attribute__ 书写特征是:__attribute__ 前后都有两个下划线,并切后面会紧跟一对原括弧,括弧里面是相应的__attribu___attribute__是哪种变量

CDH5-mysql安装_安装cdh不安装mysql-程序员宅基地

文章浏览阅读730次。0.Change Hostnamevi /etc/sysconfig/networkHOSTNAME=hadoop001(-xxx)hostname hadoop001(-xxx)vi /etc/hosts116.207.129.116 hadoop001reboot1.Download and Check MD5 cd /usr/local_安装cdh不安装mysql

Android安装GDB/GDB server_安卓13安装gdbserver-程序员宅基地

文章浏览阅读2.7k次。在没有安卓系统源码,还想调试系统代码查看崩溃信息的时候也可以用gdb或者gdbserver来调试,但是手机里没有装gdb或gdbserver。记录一下手动安装踩的坑: 首先,需要下载编译好的gdbserver。官方渠道可以从ndk-toolchain中里找,解压后在/prebuild文件夹下找对应处理器架构的版本。 然后通过adb push到手机上。貌似即使手机root之后,adb push也只_安卓13安装gdbserver

推荐文章

热门文章

相关标签