ReentrantLock重入锁

ReentrantLock初步认识

ReentrantLock是可重入的独占锁,同时只能有一个线程可以获取该锁,其他获取该锁的线程会被阻塞而放入该锁的AQS阻塞队列里面。如果当前获得该锁的线程再次获取该锁,则会记录重入次数。

ReentrantLock的类图如下:
在这里插入图片描述
从类图可以看到,ReentrantLock最终还是使用AQS来实现的,通过构造函数的参数来决定其内部是一个公平锁还是非公平锁,默认是非公平锁。

public ReentrantLock() {
    sync = new NonfairSync();
}

public ReentrantLock(boolean fair) {
    sync = fair ? new FairSync() : new NonfairSync();
}

其中Sync内部类直接继承自AQS,它的子类NonfairSync和FairSync分别实现了获取锁的非公平与公平策略。
在ReentrantLock中,AQS的state状态值表示线程获取该锁的重入次数,在默认情况下,state的值为0表示当前没有被任何线程持有。当一个线程第一次获取该锁时会尝试使用CAS设置state的值为1,如果CAS设置成功则当前线程获取了该锁,然后记录该锁的持有者为当前线程。在该线程没有释放锁的情况下第二次获取该锁后,状态值被设置为2,这就是可重入次数。在该线程释放该锁时,会尝试使用CAS让状态值减1,如果减1后状态值为0,则当前线程释放该锁。

ReentrantLock基本操作

void lock()方法

当一个线程调用该方法时,说明该线程希望获取该锁。如果锁当前没有被其他线程占用并且当前线程之前没有获取过该锁,则当前线程会获取到该锁,然后设置当前锁的拥有者为当前线程,并设置AQS的状态值为1,然后直接返回。如果当前线程之前已经获取过该锁,则把AQS的状态值加1后返回。如果该锁已经被其他线程持有,则调用该方法的线程会被放入AQS队列后阻塞挂起。

    public void lock() {
        sync.lock();
    }

在如上代码中,ReentrantLock的lock()委托给了sync类,根据ReentrantLock构建函数选择sync类的实现是NonfairSync还是FairSync,这个锁是一个非公平锁或者公平锁。
NonfairSync非公平锁:

    final void lock() {
    	// 使用CAS设置state的状态值
        if (compareAndSetState(0, 1))
        	// 设置线程持有者为当前线程
            setExclusiveOwnerThread(Thread.currentThread());
        else
        	// 调用AQS尝试获取锁
            acquire(1);
    }

在lock方法中,当前线程首先会去修改state的状态值,如果修改成功则设置线程持有者为当前线程。如果修改失败则会调用AQS的acquire()方法尝试获取锁。

    public final void acquire(int arg) {
    	// 调用ReentrantLock重写的tryAcquire方法
        if (!tryAcquire(arg) &&
        	// tryAcquire方法返回false会把当前线程放入AQS阻塞队列
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }
    protected final boolean tryAcquire(int acquires) {
        return nonfairTryAcquire(acquires);
    }

    final boolean nonfairTryAcquire(int acquires) {
        final Thread current = Thread.currentThread();
        int c = getState();
        // 当前状态值为0,表示该锁没有被其他线程持有
        if (c == 0) {
            if (compareAndSetState(0, acquires)) {
                setExclusiveOwnerThread(current);
                return true;
            }
        }
        // 当前线程是锁的持有者
        else if (current == getExclusiveOwnerThread()) {
            int nextc = c + acquires;
            if (nextc < 0) // overflow
                throw new Error("Maximum lock count exceeded");
            setState(nextc);
            return true;
        }
        // 锁已经被其他线程持有,获取锁失败,返回false
        return false;
    }

在ReentrantLock实现的tryAcquire方法中,首先获得当前的状态值,为0表示该锁没有被其他线程持有,则修改状态值并且设置当前线程为持有者。如果状态不为0,则判断当前线程是否是该锁的持有者,如果是则计入重入次数,如果不是则表示锁已经被其他线程持有,获取锁失败,将当前线程放入AQS阻塞队列。

FairSync公平锁:

 	protected final boolean tryAcquire(int acquires) {
        final Thread current = Thread.currentThread();
        int c = getState();
        // 当前状态值为0,表示该锁没有被其他线程持有
        if (c == 0) {
        	   // 使用公平性策略,返回false则继续执行
            if (!hasQueuedPredecessors() &&
                compareAndSetState(0, acquires)) {
                setExclusiveOwnerThread(current);
                return true;
            }
        }
        // 当前线程是锁的持有者
        else if (current == getExclusiveOwnerThread()) {
            int nextc = c + acquires;
            if (nextc < 0)
                throw new Error("Maximum lock count exceeded");
            setState(nextc);
            return true;
        }
        // 锁已经被其他线程持有,获取锁失败,返回false
        return false;
    }

    public final boolean hasQueuedPredecessors() {
        // The correctness of this depends on head being initialized
        // before tail and on head.next being accurate if the current
        // thread is first in queue.
        Node t = tail; // Read fields in reverse initialization order
        Node h = head;
        Node s;
        return h != t &&
            ((s = h.next) == null || s.thread != Thread.currentThread());
    }

公平锁在获取锁时,会查看当前AQS队列里面是否有比自己更早请求该锁的线程,如果有则返回true,没有则返回false。

void lockInterruptibly()方法

该方法与lock()方法类型,不同点是它对中断进行响应,就是当前线程在调用该方法时,如果其他线程调用了当前线程的interrupt()方法,则当前线程会抛出InterruptedException异常,然后返回。

    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }
    
    public final void acquireInterruptibly(int arg)
            throws InterruptedException {
        // 如果当前线程被中断,则直接抛出异常
        if (Thread.interrupted())
            throw new InterruptedException();
        if (!tryAcquire(arg))
        	// 调用AQS中断
            doAcquireInterruptibly(arg);
    }

boolean tryLock()方法

尝试获取锁,如果当前该锁没有被其他线程持有,则当前线程获取该锁并返回true,否则返回false。

    public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }
    
    final boolean nonfairTryAcquire(int acquires) {
        final Thread current = Thread.currentThread();
        int c = getState();
        if (c == 0) {
            if (compareAndSetState(0, acquires)) {
                setExclusiveOwnerThread(current);
                return true;
            }
        }
        else if (current == getExclusiveOwnerThread()) {
            int nextc = c + acquires;
            if (nextc < 0) // overflow
                throw new Error("Maximum lock count exceeded");
            setState(nextc);
            return true;
        }
        return false;
    }

该代码与非公平锁的tryAcquire()方法代码类是,所以tryLock()使用的时非公平锁策略。

boolean tryLock(long timeout, TimeUnit unit) 方法

尝试获取锁,与tryLock()的不同指出在于,它设置了超时时间,如果超时时间到了并没有获取到该锁则返回false

    public boolean tryLock(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }

void unlock()方法

尝试释放锁,如果当前线程持有该锁,则调用该方法会让线程对该线程持有的AQS状态值减1,如果减去1后当前状态为0,则当前线程会释放该锁,否则仅仅减1而已。如果当前线程没有持有该锁而调用了该方法则会抛出IllegalMonitorStateException异常。

    public void unlock() {
        sync.release(1);
    }
    
    public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }
    
    protected final boolean tryRelease(int releases) {
        int c = getState() - releases;
        // 如果不是锁持有者调用了该方法则抛出异常
        if (Thread.currentThread() != getExclusiveOwnerThread())
            throw new IllegalMonitorStateException();
        boolean free = false;
        // 如果状态值为0,则清空锁持有者线程
        if (c == 0) {
            free = true;
            setExclusiveOwnerThread(null);
        }
        setState(c);
        return free;
    }

案例

package com.wxw.lock;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDemo {

    static ReentrantLock reentrantLock = new ReentrantLock();

    static int count = 0;

    public static void incr(){
        try {
            Thread.sleep(100);
            reentrantLock.lock();
            count++;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            reentrantLock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 1000; i++){
            new Thread(ReentrantLockDemo::incr).start();
        }

        Thread.sleep(4000);
        System.out.println(count);
    }

}

ReentrantLock与ReentrantReadWriteLock的区别

解决线程安全问题使用ReentrantLock就可以,但是ReentrantLock是独占锁,只有一个线程可以获取该锁,而实际中会有写少读多的情况,这个时候就可以使用ReentrantRedWriteLock,ReentrantRedWriteLock采用读写分离的策略,允许多个线程可以同时获取读锁。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值