Java并发编程:CountDownLatch示例
CountDownLatch
是Java并发API中的一个工具类,用于协调多个线程的执行。当一个线程调用countDown()
方法时,会将计数器减1,直到计数器为0。
下面是一个简单的CountDownLatch
示例:
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) {
// 创建一个计数器,初始值为3
CountDownLatch countDown = new CountDownLatch(3);
// 创建三个线程,每个线程都会调用countDown的down方法来减少计数器
Thread thread1 = new Thread(() -> countDown.countDown());
Thread thread2 = new Thread(() -> countDown.countDown()));
Thread thread3 = new Thread(() -> countDown.countDown()));
// 启动三个线程
thread1.start();
thread2.start();
thread3.start();
// 等待计数器归零,表明所有线程都已经执行完毕
try {
countDown.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All threads have completed execution.");
}
}
在这个例子中,我们创建了一个初始值为3的CountDownLatch
。然后创建了三个线程,每个线程都会调用countDown.countDown()
来减少计数器。
当所有线程都已经完成执行时,CountDownLatch.await();
会阻塞当前线程,直到计数器归零。这意味着所有需要等待的线程已经执行完毕。
还没有评论,来说两句吧...