3.10 使用线程池时候当程序结束时候记得调用shutdown关闭线程池
日常开发中为了便于线程的有效复用,线程池是经常会被用的工具,然而线程池使用完后如果不调用shutdown会导致线程池资源一直不会被释放。下面通过简单例子来说明该问题。
3.10.1问题复现
下面通过一个例子说明当不调用线程池对象的shutdown方法后,当线程池里面的任务执行完毕后主线程这个JVM不会退出。
public class TestShutDown {
static void asynExecuteOne() {
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable() {
public void run() {
System.out.println("--async execute one ---");
}
});
}
static void asynExecuteTwo() {
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable() {
public void run() {
System.out.println("--async execute two ---");
}
});
}
public static void main(String[] args) {
//(1)同步执行
System.out.println("---sync execute---");
//(2)异步执行操作one
asynExecuteOne();
//(3)异步执行操作two
asynExecuteTwo();
//(4)执行完毕
System.out.println("---execute over---");
}
}
如上代码主线程里面首先同步执行了操作(1)然后执行操作(2)(3),操作(2)(3)使用线程池的一个线程执行异步操作,我们期望当主线程和操操作(2)(3)执行完线程池里面的任务后整个JVM就会退出,但是执行结果却如下: