线程池转换状态如下:
-
Running->Shutdown 显示调用shutdown()或隐式调用finalize()中的shutdown()
-
Running或者Shutdown->Stop 显示调用shutdownNow()
-
Shutdown->Tidying 当线程池和任务队列都是空的时候
-
-
线程池类型如下
-
newFixedThreadPool
-
创建一个核心线程数和最大线程个数为都为nThreads的线程池,并且阻塞队列的最大长度为Integer.MAX_VALUE,keyAliveTime=0说明只要当前线程个数比核心线程个数多,并且是空闲的就可以回收
public static ExecutorService newFixeThreadPool (int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newFixeThreadPool (int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory);
}
-
-
创建一个核心线程和最大线程个数都是1的线程池,并且阻塞队列长度为Integer.MAX_VALUE,keepAliveTime=0说明只要线程个数比核心线程个数多并且处于空闲状态就回收
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()), threadFactory);
}
-
-
创建一个按需创建线程的线程池,初始线程个数为0,最大线程个数为Integer.MAX_VALUE,并且阻塞队列为同步队列,keepAliveTime=60,说明只要当前线程在60s内空闲则被回收,这个类型的特殊之处在于,加入同步队列的任务会被马上执行,同步队列里面最多只有一个任务.
public static ExcecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L,TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
}
public static ExcecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L,TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory);
}
出 处:https://www.cnblogs.com/ruigege0000/p/15077722.html