首頁 > Java > java教程 > 主體

深入理解Java ThreadPoolExecutor參數的範例程式碼分析

黄舟
發布: 2017-03-23 10:25:03
原創
1798 人瀏覽過

這篇文章主要介紹了Java ThreadPoolExecutor的參數深入理解的相關資料,需要的朋友可以參考下

Java ThreadPoolExecutor的參數深入理解

#一、使用Executors建立執行緒池   

        先前建立執行緒的時候都是使用的Executors的newFixedThreadPool(),newSinglereadExecutor(),newCachedTh#Pool(ThreadExecutor(),newCachedTh#Pool(Thread 。當然Executors也是用不同的參數去new ThreadPoolExecutor

    1. newFixedThreadPool()

#    建立執行緒數固定大小的執行緒池。 由於使用了LinkedBlockingQueue所以maximumPoolSize 沒用,當corePoolSize滿了之後就加入到LinkedBlockingQueue

佇列中。每當某個執行緒執行完成之後就從LinkedBlockingQueue佇列中取一個。所以這個是創建固定大小的線程池。

 public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                   0L, TimeUnit.MILLISECONDS,
                   new LinkedBlockingQueue<Runnable>());
  }
 public ThreadPoolExecutor(int corePoolSize,
               int maximumPoolSize,
               long keepAliveTime,
               TimeUnit unit,
               BlockingQueue<Runnable> workQueue) {
   this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
       Executors.defaultThreadFactory(), defaultHandler);
  }
登入後複製

   2.newSingleThreadPool()

    建立執行緒數為1的執行緒池,由於使用了LinkedBlockingQueue所以maximumPoolSize 沒用,corePoolSize為1表示執行緒數大小為1表示執行緒數大小為1表示執行緒數1,滿了就放入佇列中,執行完了就從佇列取一個。

 public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
      (new ThreadPoolExecutor(1, 1,
                  0L, TimeUnit.MILLISECONDS,
                  new LinkedBlockingQueue<Runnable>()));
  }
登入後複製

    3.newCachedThreadPool()

    建立可緩衝的執行緒池。沒有大小限制。由於corePoolSize為0所以任務會放入SynchronousQueue隊列中,SynchronousQueue只能存放大小為1,所以會立刻新起線程,由於maxumumPoolSize為Integer.MAX_VALUE所以可以認為大小為2147483647。受記憶體大小限制。

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                   60L, TimeUnit.SECONDS,
                   new SynchronousQueue<Runnable>());
  }
public ThreadPoolExecutor(int corePoolSize,
             int maximumPoolSize,
             long keepAliveTime,
             TimeUnit unit,
             BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
       Executors.defaultThreadFactory(), defaultHandler);
  }
登入後複製

二、使用ThreadPoolExecutor建立執行緒池

ThreadPoolExecutor的

建構子

 public ThreadPoolExecutor(int corePoolSize,
               int maximumPoolSize,
               long keepAliveTime,
               TimeUnit unit,
               BlockingQueue<Runnable> workQueue,
               ThreadFactory threadFactory,
               RejectedExecutionHandler handler) {
    if (corePoolSize < 0 ||
      maximumPoolSize <= 0 ||
      maximumPoolSize < corePoolSize ||
      keepAliveTime < 0)
      throw new IllegalArgumentException();
    if (workQueue == null || threadFactory == null || handler == null)
      throw new NullPointerException();
    this.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
  }
登入後複製

參數:

        1、corePoolSize核心執行緒數大小,當執行緒數

        2、maximumPoolSize 為最大執行緒數, 當執行緒數會被放入執行階段的線程數,Qucorenablenable.中

        3、keepAliveTime  維持存活時間,當執行緒數大於corePoolSize的空閒執行緒所能維持的最大時間。

        4、unit 時間單位

        5、workQueue 保存任務的阻塞佇列

    

##任務執行順序:

        1、執行緒數小於corePoolSize時,建立執行緒執行任務。         2、當執行緒數大於等於corePoolSize且workQueue沒有滿時,放入workQueue中

##        3、執行緒數大於等於corePoolSize且當workQueue執行滿時,新執行緒執行執行數總數要小於maximumPoolSize

        4、當總線程數等於maximumPoolSize且workQueue滿了的時候執行handler的rejectedExecution。也就是拒絕策略。

ThreadPoolExecutor預設有四個拒絕策略:

        1、ThreadPoolExecutor.AbortPolicy()   直接

#拋出異常RejectedExecution#ception 2、ThreadPoolExecutor.CallerRunsPolicy()    直接呼叫run方法並且阻斷執行

        3、ThreadPoolExecutor.DiscardPolicy     3、ThreadPoolExecutor.DiscardPolicy    3、ThreadPoolExecutor.DiscardPolicy) Policy()  丟棄在佇列中隊首的任務

當然可以自己繼承

RejectedExecutionHandler來寫拒絕策略.

int corePoolSize = 1;
 int maximumPoolSize = 2;
 int keepAliveTime = 10;
// BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
 BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(5);
 ThreadFactory threadFactory = Executors.defaultThreadFactory();
 //线程池和队列满了之后的处理方式
 //1.跑出异常
 RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy(); 
 RejectedExecutionHandler handler2 = new ThreadPoolExecutor.CallerRunsPolicy();
 RejectedExecutionHandler handler3 = new ThreadPoolExecutor.DiscardPolicy();
 RejectedExecutionHandler handler4 = new ThreadPoolExecutor.DiscardOldestPolicy();

 
 ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, 
 TimeUnit.SECONDS, workQueue, threadFactory, handler2);
 
 
 for (int j = 1; j < 15; j++) {
  threadPoolExecutor.execute(new Runnable() {
  
  public void run() {
   
   try {
   System.out.println(Thread.currentThread().getName());
   TimeUnit.SECONDS.sleep(1);
   } catch (InterruptedException e) {
   e.printStackTrace();
   }
   
   
  }
  });
 }
 
 System.out.println(threadPoolExecutor);
 
 }
登入後複製

以上是深入理解Java ThreadPoolExecutor參數的範例程式碼分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!