1. CountDownLatch
1.1 說(shuō)明
一種同步輔助工具,允許一個(gè)或多個(gè)線(xiàn)程等待其他線(xiàn)程執(zhí)行的一組操作完成。
給定一個(gè)計(jì)數(shù)值。當(dāng)每個(gè)線(xiàn)程完成后,調(diào)用{@link countDown}方法給計(jì)數(shù)值減一。在當(dāng)前計(jì)數(shù)達(dá)到零之前,調(diào)用{@link#await await}方法的線(xiàn)程將一直阻塞,直到計(jì)數(shù)值為0后將釋放所有等待線(xiàn)程。
1.2 源碼
public class CountDownLatch {
/**
* Synchronization control For CountDownLatch.
* Uses AQS state to represent count.
*/
private static final class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 4982264981922014374L;
Sync(int count) {
setState(count);
}
int getCount() {
return getState();
}
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
}
private final Sync sync;
/**
* 初始化
*/
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
/**
* 導(dǎo)致當(dāng)前線(xiàn)程等待,直到count為0
*/
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
/**
* Causes the current thread to wait until the latch has counted down to
* zero, unless the thread is {@linkplain Thread#interrupt interrupted},
* or the specified waiting time elapses.
*
*/
public boolean await(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
/**
* Decrements the count of the latch, releasing all waiting threads if
* the count reaches zero.
*/
public void countDown() {
sync.releaseShared(1);
}
/**
* Returns the current count.
*
* <p>This method is typically used for debugging and testing purposes.
*
* @return the current count
*/
public long getCount() {
return sync.getCount();
}
}
1.3 示例
public class CountDownLatchDemo {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(15);
for (int i = 0; i < 15; i++) {
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
countDownLatch.countDown();
}, ""+ i).start();
}
try {
countDownLatch.await();
System.out.println("main thread");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
結(jié)果:
2. CyclicBarrier
2.1 說(shuō)明
一種同步輔助工具,允許一組線(xiàn)程全部等待對(duì)方到達(dá)一個(gè)公共屏障點(diǎn)。CyclicBarrier在涉及固定大小的線(xiàn)程方的程序中非常有用,這些線(xiàn)程偶爾必須相互等待。這個(gè)屏障被稱(chēng)為循環(huán)的,因?yàn)樗梢栽诘却木€(xiàn)程被釋放后重新使用。
CyclicBarrier支持可選的可運(yùn)行命令,該命令在參與方中的最后一個(gè)線(xiàn)程到達(dá)之后,但在釋放任何線(xiàn)程之前,在每個(gè)屏障點(diǎn)運(yùn)行一次。此屏障操作有助于在任何一方繼續(xù)之前更新共享狀態(tài)。
2.2 源碼
public class CyclicBarrier {
private static class Generation {
boolean broken = false;
}
/** The lock for guarding barrier entry */
private final ReentrantLock lock = new ReentrantLock();
/** Condition to wait on until tripped */
private final Condition trip = lock.newCondition();
//每次攔截的線(xiàn)程數(shù),在構(gòu)造時(shí)進(jìn)行賦值
private final int parties;
private final Runnable barrierCommand;
/** The current generation */
private Generation generation = new Generation();
/**
* Number of parties still waiting. Counts down from parties to 0
* on each generation. It is reset to parties on each new
* generation or when broken.
*/
private int count; //內(nèi)部計(jì)數(shù)器與parties相等
/**
* Updates state on barrier trip and wakes up everyone.
* Called only while holding lock.
*/
private void nextGeneration() {
// signal completion of last generation
trip.signalAll();
// set up next generation
count = parties;
generation = new Generation();
}
/**
* Sets current barrier generation as broken and wakes up everyone.
* Called only while holding lock.
*/
private void breakBarrier() {
generation.broken = true;
count = parties;
trip.signalAll();
}
/**
* Main barrier code, covering the various policies.
*/
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(); //若線(xiàn)程中斷,喚醒所有線(xiàn)程
throw new InterruptedException();
}
int index = --count; //計(jì)數(shù)減一
if (index == 0) { // tripped
boolean ranAction = false;
try {
final Runnable command = barrierCommand;
if (command != null)
command.run(); //執(zhí)行指定任務(wù)
ranAction = true;
nextGeneration(); //喚醒所有線(xiàn)程,轉(zhuǎn)到下一代
return 0;
} finally {
if (!ranAction)
breakBarrier();
}
}
// 如果計(jì)數(shù)器不為0則執(zhí)行此循環(huán)
for (;;) {
try {
//根據(jù)傳入的參數(shù)來(lái)決定是定時(shí)等待還是非定時(shí)等待
if (!timed)
trip.await();
else if (nanos > 0L)
nanos = trip.awaitNanos(nanos);
} catch (InterruptedException ie) {
if (g == generation && ! g.broken) {
breakBarrier();
throw ie;
} else {
// We're about to finish waiting even if we had not
// been interrupted, so this interrupt is deemed to
// "belong" to subsequent execution.
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();
}
}
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}
public CyclicBarrier(int parties) {
this(parties, null);
}
public int getParties() {
return parties;
}
public int await() throws InterruptedException, BrokenBarrierException {
try {
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}
public int await(long timeout, TimeUnit unit)
throws InterruptedException,
BrokenBarrierException,
TimeoutException {
return dowait(true, unit.toNanos(timeout));
}
public boolean isBroken() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return generation.broken;
} finally {
lock.unlock();
}
}
public void reset() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
breakBarrier(); // break the current generation
nextGeneration(); // start a new generation
} finally {
lock.unlock();
}
}
/**
* Returns the number of parties currently waiting at the barrier.
* This method is primarily useful for debugging and assertions.
*
* @return the number of parties currently blocked in {@link #await}
*/
public int getNumberWaiting() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return parties - count;
} finally {
lock.unlock();
}
}
}
應(yīng)用場(chǎng)景:多個(gè)線(xiàn)程計(jì)算最后匯總
CyclicBarrier 和CountDownLatch 區(qū)別
1.CountDownLatch 只能使用一次,CyclicBarrier 的計(jì)數(shù)器可以使用reset()方法重置。所以CyclicBarrier 可以處理更復(fù)雜的邏輯。
例如,計(jì)算發(fā)生錯(cuò)誤可以重置計(jì)數(shù)器,并讓線(xiàn)程重新執(zhí)行一次。
2.CyclicBarrier 還提供其他方法,如getNumberWaiting方法可以獲得被阻塞的線(xiàn)程數(shù)等