1.简介
在本文中,我们将给出CountDownLatch 类的指南,并演示如何在一些实际示例中使用它。
本质上,通过使用CountDownLatch,我们可以导致线程阻塞,直到其他线程完成给定任务。
2.并发编程中的用法
简而言之,CountDownLatch有一个计数器字段,您可以根据需要减少它。然后我们可以用它来阻塞一个调用线程,直到它被计数到零。
如果我们正在进行一些并行处理,我们可以使用与我们想要处理的多个线程相同的计数器值来实例化CountDownLatch。然后,我们可以在每个线程完成后调用countdown(),保证调用await()的依赖线程将阻塞,直到工作线程完成。
3.等待线程池完成
让我们通过创建一个Worker并使用CountDownLatch字段来指示它何时完成来尝试这个模式:
public class Worker implements Runnable {
private List<String> outputScraper;
private CountDownLatch countDownLatch;
public Worker(List<String> outputScraper, CountDownLatch countDownLatch) {
this.outputScraper = outputScraper;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
doSomeWork();
outputScraper.add("Counted down");
countDownLatch.countDown();
}
}
然后,让我们创建一个测试,以证明我们可以让CountDownLatch等待Worker实例完成:
@Test
public void whenParallelProcessing()throws InterruptedException {
List<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
CountDownLatch countDownLatch = new CountDownLatch(5);
List<Thread> workers = Stream.generate(() -> new Thread(new Worker(outputScraper, countDownLatch)))
.limit(5)
.collect(toList());
workers.forEach(Thread::start);
countDownLatch.await();
outputScraper.add("Latch released");
assertThat(outputScraper).containsExactly(
"Counted down",
"Counted down",
"Counted down",
"Counted down",
"Counted down",
"Latch released"
);
}
当然,“Latch release”将始终是最后一个输出 - 因为它取决于CountDownLatch的发布。
请注意,如果我们没有调用await(),我们将无法保证线程执行的顺序,因此测试会随机失败。
4. 等待开始的线程池
如果我们采用前面的例子,但是这次开始了数千个线程而不是5个线程,很可能许多早期的线程在我们甚至在后者调用start()之前已经完成了处理。这可能会使尝试重现并发问题变得困难,因为我们无法让所有线程并行运行。
为了解决这个问题,让我们让CountdownLatch的工作方式与上一个例子不同。在一些子线程完成之前,我们可以阻止每个子线程,直到所有其他子线程都已启动,而不是阻塞父线程。
让我们修改run()方法,使其在处理之前阻塞:
public class WaitingWorker implements Runnable {
private List<String> outputScraper;
private CountDownLatch readyThreadCounter;
private CountDownLatch callingThreadBlocker;
private CountDownLatch completedThreadCounter;
public WaitingWorker(
List<String> outputScraper,
CountDownLatch readyThreadCounter,
CountDownLatch callingThreadBlocker,
CountDownLatch completedThreadCounter) {
this.outputScraper = outputScraper;
this.readyThreadCounter = readyThreadCounter;
this.callingThreadBlocker = callingThreadBlocker;
this.completedThreadCounter = completedThreadCounter;
}
@Override
public void run() {
readyThreadCounter.countDown();
try {
callingThreadBlocker.await();
doSomeWork();
outputScraper.add("Counted down");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
completedThreadCounter.countDown();
}
}
}
现在,让我们修改我们的测试,使其阻塞直到所有工人都已启动,解锁工人,然后阻止直到工人完成:
@Test
public void whenDoingLotsOfThreadsInParallel() throws InterruptedException {
List<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
CountDownLatch readyThreadCounter = new CountDownLatch(5);
CountDownLatch callingThreadBlocker = new CountDownLatch(1);
CountDownLatch completedThreadCounter = new CountDownLatch(5);
List<Thread> workers = Stream.generate(() -> new Thread(new WaitingWorker(outputScraper, readyThreadCounter, callingThreadBlocker, completedThreadCounter)))
.limit(5)
.collect(toList());
workers.forEach(Thread::start);
readyThreadCounter.await();
outputScraper.add("Workers ready");
callingThreadBlocker.countDown();
completedThreadCounter.await();
outputScraper.add("Workers complete");
assertThat(outputScraper).containsExactly(
"Workers ready",
"Counted down",
"Counted down",
"Counted down",
"Counted down",
"Counted down",
"Workers complete"
);
}
这种模式对于尝试重现并发错误非常有用,因为它可以用来强制数千个线程尝试并行执行某些逻辑。
5. 尽早终止倒计时
有时,我们可能会遇到一个情况,即在CountdownLatch倒计时之前,Workers终止了错误。这可能导致它永远不会达到零并且await()永远不会终止:
@Override
public void run() {
if (true) {
throw new RuntimeException("Oh dear, I'm a BrokenWorker");
}
countDownLatch.countDown();
outputScraper.add("Counted down");
}
让我们修改我们之前的测试以使用BrokenWorker,以显示await()将如何永久阻塞:
@Test
public void whenFailingToParallelProcess()throws InterruptedException {
List<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
CountDownLatch countDownLatch = new CountDownLatch(5);
List<Thread> workers = Stream.generate(() -> new Thread(new BrokenWorker(outputScraper, countDownLatch)))
.limit(5)
.collect(toList());
workers.forEach(Thread::start);
countDownLatch.await();
}
显然,这不是我们想要的行为 - 应用程序继续比无限阻塞要好得多。
为了解决这个问题,让我们在调用await()时添加一个超时参数。
boolean completed = countDownLatch.await(3L, TimeUnit.SECONDS);
assertThat(completed).isFalse();
我们可以看到,测试最终会超时,await()将返回false。
6. 结论
在本文中,我们演示了如何使用CountDownLatch来阻塞线程,直到其他线程完成某些处理。
我们还展示了如何通过确保线程并行运行来帮助调试并发问题。
imageimage欢迎大家关注公众号:「Java知己」,关注公众号,回复「1024」你懂得,免费领取 30 本经典编程书籍。关注我,与 10 万程序员一起进步。 每天更新Java知识哦,期待你的到来!
网友评论