文章目录
ReentrantLock 是一种互斥锁,确保同一时间只有一个线程可以访问被保护的资源。当一个线程获得锁时,其他线程必须等待,直到锁被释放。Semaphore 允许多个线程同时访问共享资源,数量由许可证的计数器决定。线程在访问资源时获取许可证,许可证数量可以控制并发访问的数量。
两者都是基于AQS,ReentrantLock 互斥,Semaphore 共享。
基本使用
import java.util.concurrent.Semaphore;
public class SemaphoreExample {
private static final int MAX_AVAILABLE = 3; // 最大可用许可证
private static Semaphore semaphore = new Semaphore(MAX_AVAILABLE, true); // 公平模式
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new Worker(i)).start();
}
}
static class Worker implements Runnable {
private int id;
Worker(int id) {
this.id = id;
}
@Override
public void run() {
try {
System.out.println("Worker " + id + " is trying to acquire a permit.");
semaphore.acquire(); // 获取许可证
System.out.println("Worker " + id + " acquired a permit.");
// 模拟工作
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
System.out.println("Worker " + id + " is releasing the permit.");
semaphore.release(); // 释放许可证
}
}
}
}
工作原理
获取资源 acquire
public void acquire() throws InterruptedException {
// 直接复用 AQS 的逻辑
sync.acquireSharedInterruptibly(1);
}
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
tryAcquireShared
公平版本
protected int tryAcquireShared(int acquires) {
for (;;) {
if (hasQueuedPredecessors())
return -1;
int available = getState();
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
非公平版本
protected int tryAcquireShared(int acquires) {
return nonfairTryAcquireShared(acquires);
}
// 调用父类 Sync 的方法
final int nonfairTryAcquireShared(int acquires) {
for (;;) {
int available = getState();
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
两者区别在于公平版本先判断了一次hasQueuedPredecessors()
,如果有直接获取失败。返回值分 3 种情况
- 失败时为负值;
- 如果为 0 则表示此次获取成功,但是后续无法获取成功,因为经过本次获取已经为 0 了
- 如果共享模式下的获取成功并且后续共享模式获取也可能成功,则为正值,在这种情况下,后续等待线程必须检查可用性。
doAcquireSharedInterruptibly
获取资源失败后同样是需要入队,不过是以Node.SHARED
共享模式节点入队
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
// 入队操作
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
// 阻塞,但是这里是允许中断的
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
获取成功 setHeadAndPropagate
获取资源成功后
private void setHeadAndPropagate(Node node, int propagate) {
// 先将之前的头节点保存下来
Node h = head; // Record old head for check below
// 修改头节点,出队列
// setHead: head = node; node.thread = null; node.prev = null;
setHead(node);
// 唤醒队列后面的节点
// propagate > 0 肯定成立
if (propagate > 0 || h == null || h.waitStatus < 0 ||
(h = head) == null || h.waitStatus < 0) {
// 出队节点的 next 节点
Node s = node.next;
if (s == null || s.isShared())
doReleaseShared();
}
}
setHead(node); 这个操作即表示出队列,因为头节点是不带数据的
然后分析下唤醒队列后面的节点的条件:propagate > 0 || h == null || h.waitStatus < 0 || (h = head) == null || h.waitStatus < 0
,可以分成 3 部分来说:
propagate
首先propagate值可能是等于 0或者大于0
-
如果propagate等于0,说明已经没有资源了,只能说明当前线程获取的时候没有资源了,此时可能有其他线程释放了资源,所以要继续进行判断
-
如果propagate大于0,也就是当前线程释放的时候是还有资源的,需要唤醒后面等待的节点,尽管此时可能有其他线程将资源获取完
h == null
为什么要判断h == null
呢?
原因在于是共享模式下setHeadAndPropagate
这段代码会被多线程执行
判断h == null
条件时隐含一个条件:propagate <= 0
,也就是没资源了
这里 h 会为 null 吗?对 head 的写操作只有下图这一处,而这个 node 是不会为 null 的
因此 h 为 null 的情况只有最开始的时候,即 Semaphore 对象刚创建的时候
如果 h == null,那表示队列为空。但是由于 h 是当前线程的一个副本,可能其他线程实际上在此期间尝试获取资源被阻塞。所以还是要尝试唤醒可能存在的阻塞节点
为什么不直接读写 head 变量,而要先保存一个部分到本地变量?因为 head 是 volatile 变量
h.waitStatus < 0
同样,判断h.waitStatus < 0
,隐含条件是 propagate <= 0 && h != null
,也就是有其他线程调用了 setHead 方法
如果 h.waitStatus < 0,那么要唤醒后面可能阻塞的线程
如果 h.waitStatus >= 0,说明调用了 setHead 方法那个线程取消了获取资源(被中断了),但是仍然可能有其他线程被等待,因为此时仍然读取的是 h 这个副本,所以仍需要进一步判断
(h = head) == null || h.waitStatus < 0
这里就是重复前两步的流程了,只不过通过 head 这个 volatile 变量刷新了一下缓存
doReleaseShared
当一个线程获取到资源准备出队后,需要唤醒队列中正在阻塞的线程。这里和释放资源时的操作一样
释放资源 release
释放锁的方法对于公平版本和非公平版本都相同
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
// 在 Sync 中实现
protected final boolean tryReleaseShared(int releases) {
for (;;) {
int current = getState();
int next = current + releases;
if (next < current) // overflow
throw new Error("Maximum permit count exceeded");
if (compareAndSetState(current, next))
return true;
}
}
doReleaseShared
共享模式的释放动作,发出后续信号并确保这个信号的传播。注意:对于独占模式,如果需要信号,释放只相当于调用头节点的unparkSuccessor
。
private void doReleaseShared() {
for (;;) {
Node h = head;
if (h != null && h != tail) {
int ws = h.waitStatus;
if (ws == Node.SIGNAL) {
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
continue; // loop to recheck cases
// 唤醒后继节点
unparkSuccessor(h);
}
else if (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}
}
总结
-
ReentrantLock会调用acquireQueued(互斥),而Semaphore调用acquireShared(共享)
-
ReentrantLock的节点是互斥模式Node.EXCLUSIVE,Semaphore是共享模式Node.SHARED
-
Semaphore支持中断,ReentrantLock只有调用
lockInterruptibly
才支持中断 -
状态切换图