Fixed Thread Pool is exiting immediately, not processing threads

混江龙づ霸主 提交于 2019-12-11 19:25:43

问题


Trying to understand fixed thread pools I made this test code, which revealed the below results, contrary to what I thought it would do:

Thread Start: 1
Thread Start: 2
Thread Start: 0

That's it. No "Thread End" messages and only 3 threads were started.

I expected and I want all 10 tasks to complete.

ExecutorService exec = Executors.newFixedThreadPool(3);

for (int c = 0; c < 10; c++) {
    exec.execute(new TestThread(c));
}
exec.shutdown();

public class TestThread implements Runnable {

    private int counter;

    public TestThread (int counter) {
        this.counter = counter;
    }

    @Override
    public void run() {
        System.out.println("Thread Start: " + counter);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Thread End: " + counter);
    }
}

回答1:


exec.shutdown() doesn't block main thread. If you need to wait for all submitted tasks to finish you need to call exec.awaitTermination(1, TimeUnit.HOUR); (of course with timeout that makes sense for your application) after call to exec.shutdown();.

/**
 * Blocks until all tasks have completed execution after a shutdown
 * request, or the timeout occurs, or the current thread is
 * interrupted, whichever happens first.
 */
boolean awaitTermination(long timeout, TimeUnit unit)
    throws InterruptedException;


来源:https://stackoverflow.com/questions/52632916/fixed-thread-pool-is-exiting-immediately-not-processing-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!