質問

I am attempting to understand how to handle many instances of the ExecutorService executing Runnable commands. With regards to the code provided, how many shutdowns are required if I execute a hundred Runnables with the fixed thread pool set to one? I think the code should execute a hundred futures sequentially in the for loop execution order with a single thread (never spawns more than a single thread), and requires a single ExecutorService shutdown. Is this correct? Also, it's ok to call shutdown right after the for loop completes because all hundred of the futures are in queue so that the executorService shutdown will occur automatically after all hundred futures complete. Just looking for some clarification, thanks.

public static void main(String[] args)
{
    private static ExecutorService executorService = Executors.newFixedThreadPool(1);

    for (int i = 0; i < 100; i++)
    {
        executorService.execute(new Runnable() {
            @Override
            public void run()
            {
                // do stuff
            }
        });
    }

    executorService.shutdown();
}   
役に立ちましたか?

解決

Looks like you've got the right idea. It doesn't matter how many Runnables you've handed over to the ExecutorService to run or how big a thread pool you've allocated, you only need to call shutdown() once. That will allow all tasks to complete but will not allow you to add any new ones. You may want to call

try {
    executorService.awaitTermination(5, TimeUnit.MINUTES);
} catch (InterruptedException e) {
    // do stuff
}

to block while all tasks are completed depending on your usage scenario.

If you want to shutdown and attempt to kill all running tasks, instead call the shutdownNow() method. Note that there is no guarantee that it will be able to interrupt running tasks.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top