问题描述
如果我不调用shutdown(),那么JVM将不会自行终止.
If I will not call shutdown() then the JVM will not terminate on its own.
我的程序有什么问题或缺少什么概念?
public class ExecutorServiceExample {
public static class Task1 implements Runnable {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Message from Task1 :"
+ Thread.currentThread().getName());
}
}
public static class Task2 implements Runnable {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Message from Task2 :"
+ Thread.currentThread().getName());
}
}
public static class Task3 implements Runnable {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Message from Task3 :"
+ Thread.currentThread().getName());
}
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
Future future1 = executorService.submit(new Task1());
Future future2 = executorService.submit(new Task2());
Future future3 = executorService.submit(new Task3());
}
}
输出:
任务1发出的消息:pool-1-thread-1
Message from Task1 :pool-1-thread-1
任务3发出的消息:pool-1-thread-3
Message from Task3 :pool-1-thread-3
JVM仍然存在.如果我要调用shutdown(),那么只有JVM会死.
推荐答案
根据 Thread
javadoc :
According to Thread
javadoc:
- 已调用Runtime类的退出方法,并且安全管理器已允许进行退出操作.
- 不是守护程序线程的所有线程都已死亡,方法是从调用返回到run方法,或者引发一个传播到run方法之外的异常.
- The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
- All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
您的执行程序创建了非守护线程,以防止您的JVM关闭.执行者创建的线程通常被合并以运行提交给执行者的多个任务-通常,这是对性能的优化以重用线程,因此它们执行的任务多于一个任务(因为创建新线程是一项昂贵的操作).取决于执行程序的实现和配置(例如,请参见 ThreadPoolExecutor
文档,尤其是keepalive
配置),它可能使线程永久运行或在一段时间未使用时终止.
Your executor creates non-daemon threads which prevent your JVM from shutting down. Threads created by executors are usually pooled to run more than one task submitted to the executor - often this is a performance optimisation to reuse threads so they run more then one task (as creating new thread is an expensive operation). Depending on the implementation and configuration of the executor (e.g. see ThreadPoolExecutor
doc, especially keepalive
configuration) it might keep the threads running forever or terminate when they are unused for some time.
您必须在执行程序上调用shutdown
或使用自定义的 ThreadFactory
(例如,使用 Executors.newFixedThreadPool(int, ThreadFactory)
)中,该线程工厂将新线程配置为守护线程.
You must either call shutdown
on your executor or create it with a custom ThreadFactory
(e.g. using Executors.newFixedThreadPool(int, ThreadFactory)
) where that thread factory will configure new threads as daemon ones.
这篇关于ExecutorService JVM不会终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!