線程池

線程池

項(xiàng)目文件:HelloJava-ThreadPoolExecutorDemo

  1. 線程池優(yōu)點(diǎn):

    • 重用線程,避免創(chuàng)建和銷毀線程的性能開銷;
    • 有效控制線程池最大并發(fā)數(shù),避免大量線程之間因互相搶占系統(tǒng)資源而導(dǎo)致的阻塞現(xiàn)象;
    • 能對(duì)線程進(jìn)行簡(jiǎn)單管理,并提供定時(shí)執(zhí)行已經(jīng)間隔循環(huán)執(zhí)行等功能;
  2. 繼承關(guān)系:源于Executor;真正實(shí)現(xiàn)是ThreadPoolExecotor;

    public interface Executor {
        void execute(Runnable command);
    }
    public interface ExecutorService extends Executor {...}
    public abstract class AbstractExecutorService implements ExecutorService {...}
    public class ThreadPoolExecutor extends AbstractExecutorService {...}
    
  3. ThreadPoolExecutor

    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue
                              ThreadFactory threadFactory
                              RejectedExecutionHandler handler){
        ...
        private volatile boolean allowCoreThreadTimeOut;
        ...
    }
    
    • corePoolSize:核心線程數(shù),核心線程會(huì)在線程池中一直存活。如果allowCoreThreadTimeOut為true,閑置的核心線程等待時(shí)長(zhǎng)超過keepAliveTIme所指定的時(shí)長(zhǎng),核心線程會(huì)被終止;

    • maximumPoolSize:線程池所能容納的最大線程數(shù);

    • keepAliveTime非核心線程閑置的超時(shí)時(shí)長(zhǎng),超過時(shí)長(zhǎng),非核心線程被回收;如果allowCoreThreadTimeOut為true,同樣作用于核心線程;

    • unit: keepAliveTime參數(shù)的時(shí)間單位,枚舉值,常用TimeUnit.MILLISECONDS(毫秒)、TimeUnit.SECONDS、TimeUnit.MINUTES;

    • workQueue:任務(wù)隊(duì)列,通過線程execute方法提交的Runnable對(duì)象會(huì)存儲(chǔ)在這個(gè)參數(shù)中;

    • threadFactory:線程工廠,為線程池提供創(chuàng)建新線程的功能。

      public interface ThreadFactory {
          Thread newThread(Runnable r);
      }
      
    • RejectedExecutionHandler handler:當(dāng)線程池?zé)o法執(zhí)行新任務(wù),如任務(wù)隊(duì)列已滿或者無法成功執(zhí)行任務(wù),會(huì)調(diào)用handler.rejectedExecution,默認(rèn)拋出異常。

  4. ThreadPoolExecutor執(zhí)行流程:

    • 先開核心線程;
    • 填充任務(wù)隊(duì)列
    • 任務(wù)隊(duì)列滿了但未達(dá)到maximumPoolSize,再開非核心線程;
    • 線程池?cái)?shù)量達(dá)到線程池規(guī)定的最大值maximumPoolSize,handler拋出異常;
  5. 線程池分類:

    • FixedThreadPool:線程數(shù)量固定,只有核心線程且不會(huì)被回收;任務(wù)隊(duì)列沒有大小限制;

       public static ExecutorService newFixedThreadPool(int nThreads) {
           return new ThreadPoolExecutor(nThreads, nThreads,
                                         0L, TimeUnit.MILLISECONDS,
                                         new LinkedBlockingQueue<Runnable>());
       }
      
    • CachedThreadPool:只有非核心線程,線程數(shù)量不定;超時(shí)60s回收;SynchronousQueue可以理解為無法存儲(chǔ)元素的隊(duì)列;適合執(zhí)行大量的、耗時(shí)少的任務(wù),當(dāng)線程池閑置時(shí),線程都會(huì)被超時(shí)回收,幾乎不占用系統(tǒng)資源;

      public static ExecutorService newCachedThreadPool() {
          return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                        60L, TimeUnit.SECONDS,
                                        new SynchronousQueue<Runnable>());
      }
      
    • ScheduledThreadPool:核心線程固定,非核心線程沒有限制,非核心線程閑置立即回收(keepAliveTime為0);主要執(zhí)行定時(shí)任務(wù)周期任務(wù);schedule:計(jì)劃(表),進(jìn)度表,調(diào)度。

      public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
          return new ScheduledThreadPoolExecutor(corePoolSize);
      }
      
      public ScheduledThreadPoolExecutor(int corePoolSize) {
          super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
                new DelayedWorkQueue());
      }
      
    • SingleThreadPool只有一個(gè)核心線程;所有任務(wù)統(tǒng)一到一個(gè)線程,不需要處理線程同步問題。

      public static ExecutorService newSingleThreadExecutor() {
          return new FinalizableDelegatedExecutorService
              (new ThreadPoolExecutor(1, 1,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>()));
      }
      
  6. 通過Executors來創(chuàng)建線程池;(非Executor)

    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);
    fixedThreadPool.execute(runnable);
    
    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    cachedThreadPool.execute(runnable);
    
    ExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(4);
    scheduledThreadPool.execute(runnable);
    
    ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    singleThreadExecutor.execute(runnable);
    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容