線程池轉換狀態以下:
-
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); }