固定线程池立即退出,不处理线程

Fixed Thread Pool is exiting immediately, not processing threads

为了理解固定线程池,我编写了这段测试代码,结果如下,与我的预期相反:

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

就是这样。没有 "Thread End" 条消息,并且只启动了 3 个线程。

我预计并希望完成所有 10 个任务。

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);
    }
}

exec.shutdown() 不会阻塞主线程。如果您需要等待所有提交的任务完成,您需要在调用 exec.shutdown();.

之后调用 exec.awaitTermination(1, TimeUnit.HOUR); (当然超时对您的应用程序有意义)
/**
 * 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;