Java并发工具类:理解和使用CountDownLatch和CyclicBarrier的案例
在Java编程中,CountDownLatch和CyclicBarrier是两种常用的并发工具类。下面我们将通过实例来理解并使用它们。
- CountDownLatch
CountDownLatch最初用于线程间的同步,当一个或多个计数器为0时,会导致所有等待该事件的线程被唤醒。
案例:
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
private final CountDownLatch latch = new CountDownLatch(1);
public void waitAndSignal() throws InterruptedException {
System.out.println("Waiting for signal...");
latch.await(); // 等待计数器为0
System.out.println("Received signal and counting down...");
latch.countDown(); // 计数器减一,触发事件
System.out.println("Signal sent, waiting to exit.");
latch.await(); // 再次等待计数器为0
}
public static void main(String[] args) {
CountDownLatchExample example = new CountDownLatchExample();
example.waitAndSignal();
}
}
当运行这段代码时,主线程会先调用example.waitAndSignal()
。这里使用了CountDownLatch的await()方法来等待计数器为0。
当第二个线程(即waitAndSignal())中的计数器减一并触发事件后,所有等待这个事件的线程都会被唤醒。
在main方法中,我们创建了一个CountDownLatchExample
对象,并调用它的waitAndSignal方法,从而展示了如何使用CountDownLatch进行同步。
还没有评论,来说两句吧...