关于 Java 多线程技能的疑问

An adoubt about Java multithreading skill

看下面的代码,这里有一个关于它的问题。为什么我运行这个程序,到最后还不停? (运行 它在 eclipse 中,需要手动停止。)谁能解释为什么?

public class C1 {
    public static void main(String[] args) {
        C1 c1 = new C1();
        c1.send();
    }
    private static final int POOL_SIZE = 5;
    private ExecutorService theadPool = Executors.newFixedThreadPool(POOL_SIZE);
    public void send() {
        this.theadPool.execute(new Runnable() {
            public void run() {
                System.out.println("haha");
            }
        });
    }
}

线程池包含未标记为 "daemon" 线程的线程。当 all 非守护线程终止时,JVM 退出。您的 "main" 线程正在终止(当 main returns 时)但线程池线程仍然存在。

如果您希望程序退出,请在执行程序上调用 System.exit(...) 或调用 shutdown()


Why are the threads in thread pool still alive?

因为线程池让它们保持存活。线程池所做的其中一件事就是回收线程……因为线程创建是昂贵的。

As the thread go to the last step (System.out.println("haha");), the thread won't stop?

正确。

实际线程池线程的 run() 方法将调用您的 run() 方法。当您的 run() returns 时,线程将等待通过其他调用 execute.

提交更多任务

When all threads in thread pool come to the end, are they still alive?

嗯……线程池中的线程不会 "come to the end"。当一个任务完成后,他们等待提交另一个任务。

如果您在线程池上调用 shutdownshutdownNow,线程池线程只会最终终止。