AQS共享锁和独占锁

描述

本文使用ReentrantLockCountDownLatch演示独占锁和共享锁的实现。

AQS属性
Node head
Node tail
int status
Thread exclusiveOwnerThread

AQS内部Node属性
int waitStatus
Node prev
Node next
Thread thread
Node nextWaiter

image.png

独占锁
获取锁

  • 1线程先获取锁,设置statusexclusiveOwnerThread。1线程获取锁
  • 2线程去获取锁,发现锁已被使用,只能加入等待队列。队列先初始化一个head节点,然后将2线程封装成Node,拼接到head的next节点上,也就是tail节点。
  • 3线程去获取锁,也加入等待队列。将3线程封装成Node插入到队列尾部,也就是tail。

释放锁

  • 1线程执行完,设置status和exclusiveOwnerThread为初始值,释放锁。并叫醒head的next节点。
  • 2线程被唤醒,设置status和exclusiveOwnerThread。并将自己所在的Node的thread和prev设置为null,提升为head

共享锁
通过status标识锁

独占锁

ReentrantLock使用排他锁。AQS的status>0表示加锁,thread是当前获取锁的线程。该锁时可重入锁,所以status>0。

public static void main(String[] args) {
    final ExecutorService pool = Executors.newFixedThreadPool(3);
    final X x = new X();
    for (int i = 0; i < 3; i++) {
        pool.execute(x::m);
    }
    pool.shutdown();

}
static class X {
    private final ReentrantLock lock = new ReentrantLock();
    private int i;
    void m() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + i++);
        } finally {
            lock.unlock();
        }
    }
}

共享锁

CountDownLatch使用共享锁。AQS的status为共享锁的标记位,status>0就是加锁,等于0就是释放锁。每调用一次countDown(),status减1。
线程会阻塞在await(),直到countDown()将status置为0

public static void main(String[] args) {
    final int down = 3;
    final CountDownLatch start = new CountDownLatch(1);
    final CountDownLatch count = new CountDownLatch(down);

    final ExecutorService pool = Executors.newFixedThreadPool(down);
    for (int i = 0; i < down; i++) {
        pool.execute(new WorkerRunnable(count, start, i));
    }
    count.countDown();
    pool.shutdown();
}

static class WorkerRunnable implements Runnable {
    private final CountDownLatch doneSignal;
    private final CountDownLatch startSignal;
    private final int i;

    WorkerRunnable(CountDownLatch doneSignal, CountDownLatch startSignal, int i) {
        this.startSignal = startSignal;
        this.doneSignal = doneSignal;
        this.i = i;
    }

    public void run() {
        try {
            startSignal.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(i);
        doneSignal.countDown();
    }
}

你可能感兴趣的:(AQS共享锁和独占锁)