文章目录
CountDownLatch
允许一个或多个线程等待其他线程操作完成后才执行,底层采用共享锁实现
CountDownLatch结构
public class CountDownLatch {
//持有的同步器
private final Sync sync;
//构造方法
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
}
内部类
Sync
CountdownLatch持有的同步器
private static final class Sync extends AbstractQueuedSynchronizer {
//设置同步器state为count
Sync(int count) {
setState(count);
}
//尝试获得共享锁,当前需等待完成的线程数不为0则不能获得锁
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
//释放共享锁
protected boolean tryReleaseShared(int releases) {
// 自旋直到成功修改state
for (;;) {
int c = getState();
//如果当前需等待完成的线程数为0返回false
if (c == 0)
return false;
int nextc = c-1;
//修改当前需等待完成的线程数
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
}
主要方法
countDown()
减少需等待的线程数
//减少需等待的线程数
public void countDown() {
sync.releaseShared(1);
}
await()
存在需等待的线程则阻塞当前线程
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
getCount()
返回当前仍需等待的线程数
public long getCount() {
return sync.getCount();
}
CyclicBarrier
可循环使用的屏障,定义一组线程,线程到达屏障后被阻塞,直到一组内所有线程都到达屏障才继续执行。内部使用可重入锁和条件队列实现。
CyclicBarrier结构
public class CyclicBarrier {
//内部持有可重入锁
private final ReentrantLock lock = new ReentrantLock();
//监视器
private final Condition trip = lock.newCondition();
//参与线程个数
private final int parties;
//当所有线程都阻塞到屏障时执行的动作
private final Runnable barrierCommand;
//表示当前屏障的状态
private Generation generation = new Generation();
private static class Generation {
//屏障是否破损
boolean broken = false;
}
//未到达屏障的线程数
private int count;
//构造方法
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}
}
主要方法
await()
在阻塞线程数不等于parties时阻塞当前线程,多个线程互斥调用该方法(未竞争到锁的进入竞争队列),阻塞线程数不满足条件调用Condition.await()释放锁进入条件队列,条件满足后调用signalAll唤醒所有等待线程进入竞争队列开始竞争锁
public int await() throws InterruptedException, BrokenBarrierException {
try {
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}
private int dowait(boolean timed, long nanos)
throws InterruptedException, BrokenBarrierException,
TimeoutException {
final ReentrantLock lock = this.lock;
lock.lock();
try {
//获得当前屏障的状态
final Generation g = generation;
//如果屏障破损则抛出异常
if (g.broken)
throw new BrokenBarrierException();
if (Thread.interrupted()) {
//修改屏障状态为破损,唤醒所有等待线程
breakBarrier();
throw new InterruptedException();
}
//需等待线程-1
int index = --count;
//如果所有线程都已在屏障阻塞
if (index == 0) { // tripped
boolean ranAction = false;
try {
final Runnable command = barrierCommand;
//如果存在需要执行的动作
if (command != null)
command.run();
ranAction = true;
//唤醒所有线程,创建新的Generation,count=parties
nextGeneration();
return 0;
} finally {
if (!ranAction)
breakBarrier();
}
}
// 当前线程自旋挂起直到被唤醒或出现中断
for (;;) {
try {
//如果未设置阻塞时间则在条件队列中挂起直到被唤醒
if (!timed)
trip.await();
//设置了唤醒时间,则时间到后自动从根条件队列唤醒唤醒
else if (nanos > 0L)
nanos = trip.awaitNanos(nanos);
} catch (InterruptedException ie) {
if (g == generation && ! g.broken) {
breakBarrier();
throw ie;
} else {
Thread.currentThread().interrupt();
}
}
if (g.broken)
throw new BrokenBarrierException();
//所有线程都已到达屏障处,直接返回
if (g != generation)
return index;
//等待超时,线程仍未到达则退出屏障
if (timed && nanos <= 0L) {
breakBarrier();
throw new TimeoutException();
}
}
} finally {
lock.unlock();
}
}
//修改屏障状态为损坏,唤醒所有在屏障处等待的线程
private void breakBarrier() {
generation.broken = true;
count = parties;
trip.signalAll();
}
//重新设置下一个屏障状态
private void nextGeneration() {
//唤醒在条件队列中线程
trip.signalAll();
//设置新的屏障条件
count = parties;
generation = new Generation();
}
getNumberWaiting()
获得当前在屏障处等待的线程数
public int getNumberWaiting() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
//参与线程总数-未到达线程数
return parties - count;
} finally {
lock.unlock();
}
}
reset()
将屏障重置为初始状态。
public void reset() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
breakBarrier(); // 设置当前屏障状态为破损
nextGeneration(); // 重新为屏障设置新的状态
} finally {
lock.unlock();
}
}