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(); // 异步任务执行结束后,计数器减1
        }
    }
}

文章来源:https://blog.csdn.net/weixin_42081445/article/details/135621297
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。