import java.util.concurrent.CountDownLatch;
public class RRR {
public static void main(String[] args) throws InterruptedException {
int threadNumber = 10;
for(int j =0;j<=2;j++){
final CountDownLatch countDownLatch = new CountDownLatch(threadNumber);
for (int i = 0; i < threadNumber; i++) {
final int threadID = i;
new Thread() {
public void run() {
try {
Thread.sleep((long) (Math.random() * 10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format(
"threadID:[%s] finished!!", threadID));
countDownLatch.countDown();
}
}.start();
}
countDownLatch.await();
System.out.println("main thread finished!!");
System.out.println("还剩下"+countDownLatch.getCount() + "个子线程未执行");
}
}
}
主线程等待所有子线程执行完毕例子
最新推荐文章于 2025-12-02 21:20:38 发布
本文展示了一个使用Java的CountDownLatch来同步多个线程的例子。通过创建特定数量的线程并利用CountDownLatch来确保所有线程完成其任务后再继续执行主线程,演示了如何有效地进行线程间的同步。
7003

被折叠的 条评论
为什么被折叠?



