java如何在多线程执行完成后再执行某个方法

package com.whj.feign.client;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class Test1 {

    public static void main(String[] args) throws InterruptedException {
        final int threadCount = 10;
        final AtomicInteger count = new AtomicInteger(threadCount);
        final Object waitObject = new Object();

        ExecutorService pool = Executors.newCachedThreadPool();
        for (int i = 0; i < threadCount; i++) {
            final int j = i;
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("运行线程号:" + j);
                    synchronized (waitObject) {
                        int cnt = count.decrementAndGet();
                        if (cnt == 0) {
                            waitObject.notifyAll();
                        }

                    }
                }
            });
        }

        synchronized (waitObject) {
            while (count.get() != 0) {
                waitObject.wait();
            }
        }

        Thread.sleep(1000);
        System.out.println("结束线程");
        System.exit(0);

    }



运行结果


已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页