
public String queryAll() throws InterruptedException, ExecutionException {
long start = System.currentTimeMillis();
ExecutorService cachePool = Executors.newFixedThreadPool(1);
Future future = cachePool.submit(() -> {
return userService.queryAll();
});
while (true) {
if (future.isDone()) {
break;
}
}
List list = future.get();
//cachePool.shutdown();
System.out.println(System.currentTimeMillis() - start);
return “success”;
}
打开注释cachePool.shutdown();
可以看到线程维持稳定。。。
ExecutorService 比较重,牵扯到线程
线程的状态决定了JVM是否会回收了。
假设线程一直在运行,又是用户线程,那么肯定不会被回收。
线程结束了会被回收,是因为线程的状态被改变了。
而我们每次提交Runnable(){},实际是线程池中线程调用了其run()方法,线程本身的状态,并没有变为可回收状态。
所以线程是不会被回收的,当然也就造成了线程泄露了。
coreSize 如果为0 ,keepAliveTime之后是可以被回收的,是可以被回收的。
private shutdownExecutorService(){
//1、停止线程池接收新任务
//2、等待一定时间,让现存的任务执行结束
//3、取消当前运行的任务
//4、如果当前线程也被中断的话,那么就再次关闭线程池,同时恢复中断状态
pool.shutdown();
try{
if(!pool.awaitTermination(60,TimeUnit.SECONDS)){
pool.shutdownNow();
if(!pool.awaitTermination(60,TimeUnit.SECONDS)){
System.out.println("Pool did not terminate");
}
}
}catch(InterruptedException ie){
pool.shutdownNow();
Thread.currentTread().interrupt():
}
}