结论基本和linux c 的相同java
package com.test.api;linux
import java.util.concurrent.ArrayBlockingQueue;api
import java.util.concurrent.ExecutorService;ide
import java.util.concurrent.Executors;源码分析
import java.util.concurrent.ThreadPoolExecutor;spa
import java.util.concurrent.TimeUnit;线程
class Th implements Runnable{队列
@Override文档
public void run() {源码
while(true){
System.out.println("------------");
Thread.yield();
/*try {
Thread.sleep(1000*5);//ok
} catch (InterruptedException e) {
System.out.println("exception ");
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
}
public class Cache {
private static ExecutorService threadPool = Executors.newFixedThreadPool(4);
public static void main(String[] args) {
Th t = new Th();
/*Thread h = new Thread(t);
h.start();
h.interrupt();*/
threadPool.execute(t);
threadPool.shutdownNow();
while(true){}
}
}
shutDown()
当线程池调用该方法时,线程池的状态则马上变成SHUTDOWN状态。此时,则不能再往线程池中添加任何任务,不然将会抛出RejectedExecutionException异常。可是,此时线程池不会马上退出,直到添加到线程池中的任务都已经处理完成,才会退出。
shutdownNow()
根据JDK文档描述,大体意思是:执行该方法,线程池的状态马上变成STOP状态,并试图中止全部正在执行的线程,再也不处理还在池队列中等待的任务,固然,它会返回那些未执行的任务。
它试图终止线程的方法是经过调用Thread.interrupt()方法来实现的,可是你们知道,这种方法的做用有限,若是线程中没有sleep 、wait、Condition、定时锁等应用, interrupt()方法是没法中断当前的线程的。因此,ShutdownNow()并不表明线程池就必定当即就能退出,它可能必需要等待全部正在执行的任务都执行完成了才能退出。
上面对shutDown()以及shutDownNow()做了一个简单的、理论上的分析。若是想知道why,则须要亲自打开JDK源码,分析分析。
想要分析shutDown()以及shutDownNow()源码,我建议首先要对ThreadPoolExecutor有个大概了解。由于关闭线程池的全部方法逻辑都在ThreadPoolExecutor中处理的。
若是你真的想知道为何,建议看一下我之前写的一篇对ThreadPoolExecutor源码分析的博文,我想这对你比较透彻的了解shutDown()和shutDownNow()的区别以及java 线程池原理有很大的帮助。