import java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) throws InterruptedException {
int numberOfThreads = 3;
CountDownLatch latch = new CountDownLatch(numberOfThreads);
for (int i = 0; i < numberOfThreads; i++) {
new Thread(new AsyncTask(latch)).start();
}
latch.await(); // 等待所有异步线程执行结束
System.out.println("所有异步线程执行结束,主线程继续执行");
}
}
class AsyncTask implements Runnable {
private final CountDownLatch latch;
public AsyncTask(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
// 模拟异步任务执行时间
Thread.sleep((long) (Math.random() * 1000));
System.out.println(Thread.currentThread().getName() + " 异步任务执行结束");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown(); // 异步任务执行结束后,计数器减1
}
}
}
Java 主线程等待所有异步线程执行结束后在继续执行
最新推荐文章于 2024-05-31 16:50:28 发布
该篇文章介绍了如何在Java中使用CountDownLatch实现线程间的同步,创建了一个包含多个异步任务的示例,确保主线程在所有异步任务完成后继续执行。
摘要由CSDN通过智能技术生成