import java.util.concurrent.CountDownLatch;
public class CountdownLatchExample {
public static void main(String[] args) throws InterruptedException {
// 创建一个CountDownLatch,参数为3,表示需要等待3个线程完成
CountDownLatch latch = new CountDownLatch(3);
// 创建并启动三个线程
for (int i = 0; i < 3; i++) {
new Thread(new Worker(latch)).start();
}
// 主线程等待所有子线程完成
System.out.println("主线程等待所有子线程完成...");
latch.await(); // 阻塞直到计数器归零
System.out.println("所有子线程已完成,主线程继续执行...");
}
// 子线程任务类
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() + " 正在工作...");
Thread.sleep(1000); // 模拟耗时操作
System.out.println(Thread.currentThread().getName() + " 工作完成");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 子线程完成工作后,调用countDown方法减少计数器
latch.countDown();
}
}
}
}
CountDownLatch 是一个同步辅助类,它允许一个或多个线程一直等待,直到其他线程执行完一组操作。CountDownLatch 对象,初始值为3,表示需要等待3个线程完成它们的任务。Thread.sleep 模拟耗时操作),并在完成工作后调用 latch.countDown() 方法来减少计数器。latch.await() 方法,阻塞等待直到计数器归零(即所有子线程完成工作)。countDown() 方法后,await() 方法返回,主线程继续执行。下一篇:java 生成uuid
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站