import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) {
// 创建一个计数器,初始值为3,表示需要等待3个线程完成
CountDownLatch latch = new CountDownLatch(3);
// 创建并启动三个线程
for (int i = 0; i < 3; i++) {
new Thread(new Worker(latch)).start();
}
try {
// 主线程等待所有子线程完成
System.out.println("Main thread is waiting for all workers to finish.");
latch.await(); // 阻塞直到计数器归零
System.out.println("All workers have finished.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 工作者线程类
static class Worker implements Runnable {
private final CountDownLatch latch;
public Worker(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
// 模拟工作
System.out.println(Thread.currentThread().getName() + " is working...");
Thread.sleep(1000); // 模拟耗时任务
System.out.println(Thread.currentThread().getName() + " has finished.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 工作完成后减少计数器
latch.countDown();
}
}
}
}
CountDownLatch初始化:CountDownLatch latch = new CountDownLatch(3);
创建了一个 CountDownLatch
对象,初始计数值为3,表示需要等待3个线程完成。
启动线程:通过循环创建并启动了3个线程,每个线程都执行 Worker
类中的任务。
主线程等待:latch.await();
让主线程阻塞,直到 CountDownLatch
的计数值变为0。也就是说,主线程会一直等待,直到所有子线程完成任务。
子线程执行任务:每个子线程在 Worker
类的 run()
方法中模拟了一些工作(例如打印信息和休眠),并在任务完成后调用 latch.countDown();
减少计数器的值。
计数器归零:当所有子线程都完成了任务并调用了 countDown()
方法后,计数器归零,await()
方法返回,主线程继续执行后续代码。
这个例子展示了如何使用 CountDownLatch
来协调多个线程的执行顺序,确保某些操作在所有指定的任务完成后才进行。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站