Java Thread.join() 在执行程序中等效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20495414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:20:24  来源:igfitidea点击:

Thread.join() equivalent in executor

javamultithreadingexecutorservice

提问by Mario Stoilov

I have a newbie question. I have this code:

我有一个新手问题。我有这个代码:

public class Main 
{

    public static void main(String[] args) throws InterruptedException 
    {
        // TODO Auto-generated method stub
        IntHolder aHolder=new IntHolder();
        aHolder.Number=0;

        IncrementorThread A= new IncrementorThread(1, aHolder);
        IncrementorThread B= new IncrementorThread(2, aHolder);
        IncrementorThread C= new IncrementorThread(3, aHolder);

        A.start();
        B.start();
        C.start();

        A.join();
        B.join();
        C.join();
        System.out.println("All threads completed...");

    }

}

Which will wait for all threads to complete. If I use Executorslike this:

这将等待所有线程完成。如果我这样使用Executors

public class Main 
{

    public static void main(String[] args) 
    {
        // TODO Auto-generated method stub
        IntHolder aHolder=new IntHolder();
        aHolder.number=0;

        IncrementalRunable A= new IncrementalRunable(1, aHolder);
        IncrementalRunable B= new IncrementalRunable(2, aHolder);
        IncrementalRunable C= new IncrementalRunable(3, aHolder);

        ExecutorService exec = Executors.newFixedThreadPool(3);
        exec.execute(A);
        exec.execute(B);
        exec.execute(C);
        //Don't know what to do here

        System.out.println("All threads completed...");
    }
}

How can I suspend the main thread to wait for all the threads in the executor to finish, i.e the "All threads completed..." should be printed after the all the threads have done their work?

如何挂起主线程以等待执行程序中的所有线程完成,即在所有线程完成工作后应打印“所有线程已完成...”?

采纳答案by Narendra Pathai

executor.shutdown();
while (!executor.awaitTermination(24L, TimeUnit.HOURS)) {
    System.out.println("Not yet. Still waiting for termination");
}

Use shutdown() + awaitTermination()combination.

使用shutdown() + awaitTermination()组合。

EDIT:

编辑:

Based on the comment of @Lital

基于@Lital的评论

List<Callable<Object>> calls = new ArrayList<Callable<Object>>();
calls.add(Executors.callable(new IncrementalRunable(1, aHolder)));
calls.add(Executors.callable(new IncrementalRunable(2, aHolder)));
calls.add(Executors.callable(new IncrementalRunable(3, aHolder)));

List<Future<Object>> futures = executor.invokeAll(calls);

NOTE: invokeAll()will not return until all the tasks are completed (either by failing or completing successful execution).

注意: invokeAll()在所有任务完成之前不会返回(通过失败或完成成功执行)。

回答by Satheesh Cheveri

 exec.shutdown();
    // Wait until all threads are finish
    exec.awaitTermination();

回答by Lital Kolog

You shouldn't use executor like this if you want to wait for tasks to finish. What if you don't want/can't shutdown your thread pool executor? This is a more recommended way:

如果你想等待任务完成,你不应该像这样使用 executor。如果您不想/不能关闭线程池执行程序怎么办?这是更推荐的方式:

    ExecutorService exec = Executors.newFixedThreadPool(3);
    Collection<Future<?>> tasks = new LinkedList<Future<?>>();

    Future<T> future = exec.submit(A);
    tasks.add(future);
    future = exec.submit(B);
    tasks.add(future);
    future = exec.submit(C);
    tasks.add(future);

    // wait for tasks completion
    for (Future<?> currTask : tasks) {
            try {
                currTask.get();
            } catch (Throwable thrown) {
                Logger.error(thrown, "Error while waiting for thread completion");
            }
        }

回答by Abdul Rasheed Mohammed

Try working with thread pool this way.

尝试以这种方式使用线程池。

executor.shutdown();
executor.awaitTermination(MAX_PRIORITY, TimeUnit.HOURS);

回答by Rakesh Singh Balhara

We can use below code to join the thread.

我们可以使用下面的代码来加入线程。

 executor.execute(new YouThread());

    try{     
         executor.shutdown();
         while (!executor.awaitTermination(24L, TimeUnit.HOURS)) {
             System.out.println("Not yet. Still waiting for termination");
         }                
    }catch(InterruptedException e){
        e.printStackTrace();
    }