java - 等待主线程直到 ExecutorService 的所有线程池任务完成?

标签 java multithreading

我需要主线程等待所有线程池任务完成。怎么做?例如: 我有程序:

  public static void main(String[] args){

        ExecutorService executor = Executors.newFixedThreadPool(2);
        Map<String,String> test = new HashMap<String,String>(){{
            put("a","b");
            put("c","b");

        }};
        for(String t: test.keySet()) {
            executor.execute(new Runnable() {
                public void run() {
                    for(int i=0;i<100;i++){
                        System.out.println("t = " + t);
                    }

                }
            })
            ;
        }

        executor.shutdown();

        System.out.println("outside");;
    }

在上面的代码中,我想始终在最后打印“外部”,即在 ExecutorService 任务完成后。

最佳答案

您正在寻找的方法正是

<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
                          throws InterruptedException

来自 javadocs,

Executes the given tasks, returning a list of Futures holding their status and results when all complete. Future.isDone() is true for each element of the returned list. Note that a completed task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.

但是,您需要转换 RunnableList<Callable<Void>>来利用这个。

另外,在生产中使用代码时,我会使用超时来保持理智,该代码的方法签名为

<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
                            long timeout,
                            TimeUnit unit)
                          throws InterruptedException

为了理智!

关于java - 等待主线程直到 ExecutorService 的所有线程池任务完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56523008/

相关文章:

c++ - 在Linux上的C++中使用线程应该添加哪个头文件

java - 将鼠标悬停在 JSplitPane 分隔线上时更改光标

java - ScheduledExecutorService 只循环一次

python - 在推理服务中使用 tf.Session 时它是线程安全的吗?

java - 异常 java.lang.NoClassDefFoundError JavaMail Tomcat v8.5

c++ - cmake 不使用 boost 多线程库

java - 两个线程获得相同的值

java - 单点注销配置文件 Idp 注销问题

java - 如何在使用比较器接口(interface)时获取矩形对象的数组列表以显示每个矩形的面积

java - 如何从 Java 调用 Lua 脚本