Java并发工具类:理解和使用CountDownLatch和CyclicBarrier的案例

原创 柔光的暖阳◎ 2024-12-01 13:51 32阅读 0赞

在Java编程中,CountDownLatch和CyclicBarrier是两种常用的并发工具类。下面我们将通过实例来理解并使用它们。

  1. CountDownLatch

CountDownLatch最初用于线程间的同步,当一个或多个计数器为0时,会导致所有等待该事件的线程被唤醒。

案例:

  1. import java.util.concurrent.CountDownLatch;
  2. public class CountDownLatchExample {
  3. private final CountDownLatch latch = new CountDownLatch(1);
  4. public void waitAndSignal() throws InterruptedException {
  5. System.out.println("Waiting for signal...");
  6. latch.await(); // 等待计数器为0
  7. System.out.println("Received signal and counting down...");
  8. latch.countDown(); // 计数器减一,触发事件
  9. System.out.println("Signal sent, waiting to exit.");
  10. latch.await(); // 再次等待计数器为0
  11. }
  12. public static void main(String[] args) {
  13. CountDownLatchExample example = new CountDownLatchExample();
  14. example.waitAndSignal();
  15. }
  16. }

当运行这段代码时,主线程会先调用example.waitAndSignal()。这里使用了CountDownLatch的await()方法来等待计数器为0。

当第二个线程(即waitAndSignal())中的计数器减一并触发事件后,所有等待这个事件的线程都会被唤醒。

在main方法中,我们创建了一个CountDownLatchExample对象,并调用它的waitAndSignal方法,从而展示了如何使用CountDownLatch进行同步。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,32人围观)

还没有评论,来说两句吧...

相关阅读