在关闭执行程序之前等待所有线程完成

在关闭执行程序之前等待所有线程完成

问题描述:

这是我的代码段。

ExecutorService executor = Executors.newFixedThreadPool(ThreadPoolSize);
while(conditionTrue)
{
ClassImplementingRunnable c = new ClassImplementingRunnable();
executor.submit(c);
}

此后再做

executor.shutdown();

我想在这里实现的是我想等待线程池中的所有线程都有完成执行,然后我想关闭执行程序。

What i want to achieve here is that i want to wait for all the threads in the threadpool to have finished the execution and then i want to shutdown the executor.

但我想这不是这里发生的事情。主线程似乎正在执行关闭,它只是关闭所有内容。

But i guess this is not what is happening here. The main thread seems to be executing shutdown and it just shuts down everything.

在我的线程池大小为2之前,我做了以下操作,它似乎工作。

Before when my threadpool size was 2, i did the following and it seemed to work.

ClassImplementingRunnable c1 = new ClassImplementingRunnable();
executor.submit(c1);
ClassImplementingRunnable c2 = new ClassImplementingRunnable();
executor.submit(c2);
Future f1 = executor.submit(c1);
Future f2 = executor.submit(c2);
while(!f1.done || !f2.done)
{}
executor.submit();

我如何为线程池中的更多线程执行此操作?
谢谢。

How do i do this for a greater number of threads in the threadpool? Thanks.

您通常使用以下习语:

executor.shutdown();
executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);




  • shutdown 只是说遗嘱执行人赢了接受新工作。

  • awaitTermination 等待所有已提交的任务完成他们正在做的事情(或者直到达到超时 - 这对于Integer.MAX_VALUE不会发生 - 你可能想要使用更低的值。)

    • shutdown just says that the executor won't accept new jobs.
    • awaitTermination waits until all the tasks that have already been submitted finish what they are doing (or until the timeout is reached - which won't happen with Integer.MAX_VALUE - you might want to use a lower value).