一、Semaphore
Semaphore信号量–同CountDownLatch和CycleBarrier类似,但是它的计时器是递增的。
二、源码分析
2.1 继承关系
有3个内部类,实现了公平锁和非公平锁,关系如下。会不会有点眼熟,很像ReentrantLock的公平锁和非公平锁的实现。
2.2 属性
属性很简单
private static final long serialVersionUID = -3222578661600680210L;
/** Sync引用 */
private final Sync sync;
2.3 构造方法
两个构造方法,其实就是选择公平锁和非公平锁以及信号量大小
public Semaphore(int permits) {
sync = new NonfairSync(permits);
}
public Semaphore(int permits, boolean fair) {
sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}
先看下公平锁的构造方法
static final class FairSync extends Sync {
FairSync(int permits) {
super(permits);
}
...
}
看下父类的构造器,将信号量传给了AQS的state
Sync(int permits) {
setState(permits);
}
非公平锁的构造方法,其实和公平锁一样
NonfairSync(int permits) {
super(permits);
}
2.4 常用方法
2.4.1 void accquire()方法
public void acquire() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
调用了AQS的方法
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
//如果线程被中断,抛出异常
if (Thread.interrupted())
throw new InterruptedException();
//tryAcquireShared需要子类去实现
//如果<0 条件为true,进入if,代表信号量还不够
if (tryAcquireShared(arg) < 0)
//将线程放入阻塞队列
doAcquireSharedInterruptibly(arg);
}
先看下非公平锁的tryAcquireShared实现
protected int tryAcquireShared(int acquires) {
return nonfairTryAcquireShared(acquires);
}
final int nonfairTryAcquireShared(int acquires) {
//死循环
for (;;) {
//获取AQS的state
int available = getState();
//remaining = 现在的state - 传入的信号量
int remaining = available - acquires;
//负数,不为负数则设置state=remaining
if (remaining < 0 ||
compareAndSetState(available, remaining))
//返回remaining
return remaining;
}
}
公平锁的tryAcquireShared实现
protected int tryAcquireShared(int acquires) {
for (;;) {
//如果阻塞队列有后继节点
if (hasQueuedPredecessors())
//返回-1,后续将线程加入阻塞队列
return -1;
//如果没有则尝试获取
int available = getState();
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
传参设置信号量,基本跟上面的一样了
public void acquire(int permits) throws InterruptedException {
if (permits < 0) throw new IllegalArgumentException();
sync.acquireSharedInterruptibly(permits);
}
2.4.2 void release()方法
public void release() {
sync.releaseShared(1);
}
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
//唤醒节点
doReleaseShared();
return true;
}
return false;
}
子类实现的方法
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;
}
}
三、总结
Semaphore也可以达到CountDownLatch的效果,但是计数器不能自动重置,主要还是用于流量控制,有公平策略和非公平策略
实例:
模拟一个连接池,只有10个线程,但是进来了50个请求,使用Semaphore做流量控制
package com.cf.test.lock;
import java.util.concurrent.Semaphore;
public class SemaphoreDemo {
static int count = 1;
public static void main(String[] args) throws InterruptedException {
Semaphore semaphore = new Semaphore(10);
for(int i = 0; i < 50; i++){
int j =i;
new Thread(() -> {
try {
long time = (long) (Math.random() * 10000);
semaphore.acquire();
System.out.println("线程" + j + "进入了连接池,花费" + time/1000 + "秒完成了任务");
Thread.sleep(time);
count++;
System.out.println("线程" + j + "出了连接池");
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
semaphore.acquire(10);
System.out.println(count);
}
}
结果: