線程池

線程池好處:java

  • 下降資源消耗
  • 提升響應速度
  • 提升線程的可管理性

execute的邏輯:框架

  1. 若是當前運行線程少於coolPoolSize,建立新線程來執行(須要得到全局鎖)
  2. 線程多餘corePoolSize,則將任務加入BlockingQueue
  3. 當BlockingQueue已滿,則建立新線程處理(須要得到全局鎖)
  4. 若是建立線程時線程數超過maximumPoolSize,任務將被拒絕,並調用handle的rejectedExecution()方法

 

線程池會將傳入的Runnable封裝成Worker,執行完後自動獲取阻塞隊列的下一個Runnable異步

 

線程池構造方法ui

ThreadPoolExecutor(int corePoolSize,

int maximumPoolSize,

long keepAliveTime,

TimeUnit unit,

BlockingQueue<Runnable> workQueue,

ThreadFactory threadFactory,

RejectedExecutionHandler handler)
  • corePoolSize線程池核心線程數,當提交任務時發現線程數小於這個數,將直接建立新線程執行任務,即便有空餘線程也會建立新的,若是調用了線程池的prestartAllCoreThreads()將提早建立好指定個數的線程(執行這一步須要得到全局鎖)
  • maximumPoolSize線程池最大線程數
  • keepAliveTime線程空閒後,存活時間
  • unit時間單位
  • workQueue任務隊列,若是傳入的是無界隊列,那maximumPoolSize無效
  • threadFactory用於設置建立線程的工廠,能夠用來給線程設置有意義的名字,如使用guava:new ThreadFactoryBuilder().setNameFormat("xx-task-%d").build();
  • handler當線程和隊列都滿了後的處理策略,jdk的實現類:
    • AbortPolicy:直接拋出異常
    • CallerRunsPolicy:只用調用者所在線程來運行任務
    • DiscardOldestPolicy丟棄隊列最近的一個任務,並執行當前任務
    • Discardpolicy不處理,丟棄掉

線程池執行Runnable有兩個方法:execute(Runnable task)和submit(Runnable task)兩個方法,區別是submit會返回一個Feature對象,Feature對象能夠調用get()獲取返回值,會阻塞當前線程直到任務完成,同時提供了get(long timeout, TimeUnit unit)超時拋出TimeOutException脫離阻塞。線程

 

Executor框架主要由3大部分組成:rest

  • 任務,實現了Runnable或Callable接口
  • 任務的執行,實現Executor接口或繼承自Executor的ExecutorService接口
  • 異步計算的結果,包括接口Future和時間Future接口的FutureTask類

 

 

ThreadPoolExecutor一般使用工廠類Executors來建立,能夠建立3種類型的SingleThreadExecutor、FixedThreadPool、CachedThreadPoolcode

 

FixedThreadPool:orm

public static ExecutorService newFixedThreadPool(int nThreads){
  return new ThreadPoolExecutor(nThreads, nThreads, 0L, 
  TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
}

corePoolSize = maximumPoolSize, keepAliveTime = 0L, 使用無界LinkedBlockingQueue對象

 

SingleThreadExecutor:繼承

 

public static ExecutorService newSingleThreadPool(){
  return new FinalizableDelegatedExecutorService(
    new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, 
      new LinkedBlockingQueue<Runnable>()));
}

 

CachedThreadPool:

public static ExecutorService newCachedThreadPool(){
  return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, 
  TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
}
相關文章
相關標籤/搜索