Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 等待主线程,直到ExecutorService的所有线程池任务完成?_Java_Multithreading - Fatal编程技术网

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

Java 等待主线程,直到ExecutorService的所有线程池任务完成?,java,multithreading,Java,Multithreading,我需要主线程等待所有线程池任务完成。怎么做?例如: 我有一个计划: public static void main(String[] args){ ExecutorService executor = Executors.newFixedThreadPool(2); Map<String,String> test = new HashMap<String,String>(){{ put("a","b");

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

  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");;
    }
publicstaticvoidmain(字符串[]args){
ExecutorService executor=Executors.newFixedThreadPool(2);
Map test=newhashmap(){{
付诸表决(“a”、“b”);
付诸表决(“c”、“b”);
}};
for(字符串t:test.keySet()){
executor.execute(新的Runnable(){
公开募捐{
对于(int i=0;i您可以使用而不是执行器。这是阻止调用线程,直到它被倒计时为零。或者您可以使用。主要区别是CyclicBarrier可以重置并再次使用


.

使用执行器时,我们可以通过调用shutdown()或shutdownNow()方法将其关闭。 尽管如此,它不会等到所有线程停止执行(这就是为什么在代码中,“外部”是先打印的,而不是最后打印的)。
等待现有线程完成其执行可以通过使用waitTermination()方法来实现,该方法会阻止线程,直到所有任务完成其执行或达到指定的超时

改变

executor.shutdown();

executor.shutdown();
试一试{
如果(!执行器等待终止(60,时间单位秒)){
执行者。关机现在();
}
}捕获(中断异常例外){
执行者。关机现在();
Thread.currentThread().interrupt();
}

您正在寻找的方法正是

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

为了理智起见!

executor.awaitTermination
?(在关闭调用后)awaitTermination()预期超时参数,我希望在不传递超时值的情况下执行。有解决方案吗?使用不合理的超时值调用它(如100年毫秒)然后使用Callable而不是runnable。并使用get()或isDone()阻塞方法。这将阻止主线程,直到您从线程获得结果。这样,您也不必关闭执行器(如果您仍然需要它来执行其他事情)。
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
                            long timeout,
                            TimeUnit unit)
                          throws InterruptedException