美文网首页
ReentrantLock笔记

ReentrantLock笔记

作者: 枫叶无言 | 来源:发表于2018-08-10 08:51 被阅读0次

简介

ReentrantLock:可重入锁。

该锁支持一个线程对资源的重复加锁。另外,在获取锁时支持公平和非公平的选择。

·公平锁:根据当前线程的等待时间分配锁,即FIFO的方式,不会出现某个线程等待时间过长的情况,减少”饥饿“发生的概率,但是依赖操作系统,所以吞吐量不如非公平锁。

·非公平锁:可能出现”饥饿“现象,是无序的锁竞争,刚释放锁的线程很大程度上能比较快的获取到锁,所以效率比较高。

和synchronized关键字不同,synchronized关键字隐式地支持重进入。其中,

特性             synchronized              Lock

锁获取超时     不支持                  支持

获取锁响应中断    不支持            支持

主要方法

·构造方法

支持实现fair-公平锁/非公平锁

·public boolean tryLock()  

获取锁,通过compareAndSetState方法实现。

/**

    * Atomically update Java variable to x if it is currently

    * holding expected.

    * @return true if successful

    */

    public final native boolean compareAndSwapInt(Object o, long offset, int expected, int x);

以CAS的方式将制定字段设置为指定的值。

·public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException

可中断的支持再一个时间段内获取该锁。

·Protected Thread getOwner();

该方法声明为Protected,只有子类继承自ReentrantLock类,并override该方法才能使用。

相关文章

网友评论

      本文标题:ReentrantLock笔记

      本文链接:https://www.haomeiwen.com/subject/udxhbftx.html