Java多线程系列(十)—Semaphore源码分析
Semaphore是计数信号量,用来控制并发数量,允许n个任务同时访问某个资源,可以将信号量看做是在向外分发使用资源的许可,只有成功获取许可才能使用资源;
个人主页:tuzhenyu’s page
原文地址:Java多线程系列(十)—Semaphore源码分析
(0) Semaphore信号量的使用
三个线程循环打印
class ThreadA extends Thread{
private Semaphore semaphoreA;
private Semaphore semaphoreB;
public ThreadA(String name,Semaphore semaphoreA,Semaphore semaphoreB){
super(name);
this.semaphoreA = semaphoreA;
this.semaphoreB = semaphoreB;
}
@Override
public void run() {
try {
for (int i=0;i<10;i++){
semaphoreA.acquire();
System.out.println(Thread.currentThread().getName());
semaphoreB.release();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
class ThreadB extends Thread{
private Semaphore semaphoreB;
private Semaphore semaphoreC;
public ThreadB(String name,Semaphore semaphoreB,Semaphore semaphoreC){
super(name);
this.semaphoreB = semaphoreB;
this.semaphoreC = semaphoreC;
}
@Override
public void run() {
try {
for (int i=0;i<10;i++){
semaphoreB.acquire();
System.out.println(Thread.currentThread().getName());
semaphoreC.release();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
class ThreadC extends Thread{
private Semaphore semaphoreC;
private Semaphore semaphoreA;
public ThreadC(String name,Semaphore semaphoreC,Semaphore semaphoreA){
super(name);
this.semaphoreC = semaphoreC;
this.semaphoreA = semaphoreA;
}
@Override
public void run() {
try {
for (int i=0;i<10;i++){
semaphoreC.acquire();
System.out.println(Thread.currentThread().getName());
semaphoreA.release();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
public class SemaphoreDemo {
public static void main(String[] args) {
Semaphore semaphoreA = new Semaphore(1);
Semaphore semaphoreB = new Semaphore(0);
Semaphore semaphoreC = new Semaphore(0);
ThreadA threadA = new ThreadA("A",semaphoreA,semaphoreB);
ThreadB threadB = new ThreadB("B",semaphoreB,semaphoreC);
ThreadC threadC = new ThreadC("C",semaphoreC,semaphoreA);
threadA.start();
threadB.start();
threadC.start();
}
}
(1) Semaphore信号量的常用方法
// 创建具有给定的许可数和非公平设置的 Semaphore。
Semaphore(int permits)
// 创建具有给定的许可数和给定的公平设置的 Semaphore。
Semaphore(int permits, boolean fair)
// 创建具有给定的许可数和非公平的公平设置的 Semaphore。
Semaphore(int permits)
// 创建具有给定的许可数和给定的公平设置的 Semaphore。
Semaphore(int permits, boolean fair)
// 释放一个许可,将其返回给信号量。
void release()
// 释放给定数目的许可,将其返回到信号量。
void release(int permits)
(2) Semaphore信号量的类结构
Semaphore信号量的实现和ReetrantLock类似,都是通过内部类Sync,Sync是一个继承于AQS的抽象类;
Semaphore信号量和ReentrantLock互斥锁的实现区别在于,ReentrantLock互斥锁的state如果为0则表示锁未被占用,如果为0之外的数值表示锁被重入的次数;Semaphore信号量的state表示许可的数目,可以有很多种值;
Sync包括两个子类:公平信号量FairSync和非公平信号量NonfailrSync,默认是非公平信号量NonfairSync;
公平信号量是指如果线程不在同步队列头部则排队等候;
非公平信号量是指无论当前线程是否在同步队列头部,都会尝试获取信号量;
(3) Semaphore信号量的语义实现
1. Semaphore信号量的实例化
- 指定许可数量,不指定信号量类型,默认是非公平信号量
public Semaphore(int permits) {
sync = new NonfairSync(permits);
}
- 指定许可数目和信号量类型
public Semaphore(int permits, boolean fair) {
sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}
2. Semaphore非公平信号量的获取
- 非公平信号量获取的流程
- 从信号量中获取一个或多个许可
public void acquire() throws InterruptedEx ception {
sync.acquireSharedInterruptibly(1);
}
public void acquire(int permits) throws InterruptedException {
if (permits < 0) throw new IllegalArgumentException();
sync.acquireSharedInterruptibly(permits);
}
- 调用acquireSharedInterruptibly()方法实现许可的获取
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
- 调用tryRequireShared()方法尝试获取信号量
protected int tryAcquireShared(int acquires) {
return nonfairTryAcquireShared(acquires);
}
判断减去许可请求后state的数量
final int nonfairTryAcquireShared(int acquires) {
for (;;) {
int available = getState();
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
- 尝试获取信号量失败后调用doAcquireSharedInterruptibly()方法将当前线程放入同步队列中,并判断当前线程节点是否为头结点下一节点,如果是则再次尝试获取许可,否则将线程阻塞放入同步队列尾部;
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);
}
}
3. Semaphore公平信号量的获取
公平信号量的获取与非公平信号量的获取区别在于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;
}
}
4. Semaphore信号量的释放
- 信号量的释放流程
- 公平信号量和非公平信号量的释放都是通过release()方法实现的
public void release() {
sync.releaseShared(1);
}
释放特定数量的许可
public void release(int permits) {
if (permits < 0) throw new IllegalArgumentException();
sync.releaseShared(permits);
}
调用releaseShared()方法释放许可
首先通过调用tryReleaseShared()方法尝试释放许可
然后通过doReleaseShared()方法唤醒同步队列中的所有线程
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
首先通过调用tryReleaseShared()方法尝试释放许可
- 当前许可数目加上释放的许可数目,判断是否溢出,最大为Integer.Max_Vlaue
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()方法从前到后遍历CLH队列,依次唤醒同步队列中的所有阻塞线程;唤醒的线程继续尝试获取许可,如果获取失败则会再次阻塞进入同步队列;
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;
}
}
总结
Semaphore信号量的底层实现原理与ReentrantLock类似,都是通过内部类Sync和两个子类FairSync公平锁和NonfairSync非公平锁;区别在于ReentrantLock的state的值表示被重入的此时,而Semaphore的state值表示许可的剩余量;如果ReentrantLock的state为0表示锁未被占用,而Semaphore的state为0则会表示许可剩余为0会造成线程的阻塞;
Semaphore信号量的实现主要是通过acquire(),acquire(int permits)方法和release(),release(int permits)方法等;
Semaphore信号量的实现和CountDownLatch底层原理类似,都是通过共享锁的获取和释放;