Java高併發28-ThreadPoolExecutor原理剖析(2)

線程池轉換狀態如下:

  • Running->Shutdown 顯示調用shutdown()或隱式調用finalize()中的shutdown()
  • Running或者Shutdown->Stop 顯示調用shutdownNow()
  • Shutdown->Tidying 當線程池和任務隊列都是空的時候
  • Stop ->Tidying
  • Tidying -> Terminated

線程池類型如下

  • 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);
 }
  • newSingleThreadExecutor
  • 創建一個核心線程和最大線程個數都是1的線程池,並且阻塞隊列長度爲Integer.MAX_VALUE,keepAliveTime=0說明只要線程個數比核心線程個數多並且處於空閒狀態就回收
 public static ExecutorService newSingleThreadExecutor() {
  return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(110L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()));
 }
 
 // 使用自己的工廠
 public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
  return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(110L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()), threadFactory);
 }
  • newCachedThreadPool
  • 創建一個按需創建線程的線程池,初始線程個數爲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);
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章