Java 主线程等待所有异步线程执行结束后在继续执行
发布时间:2024年01月16日
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();
}
}
}
文章来源:https://blog.csdn.net/weixin_42081445/article/details/135621297
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:chenni525@qq.com进行投诉反馈,一经查实,立即删除!