1. 程式人生 > 其它 >java 執行緒池引數

java 執行緒池引數

建立執行緒池的建構函式如下:

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.acc = System.getSecurityManager() == null ? null : AccessController.getContext(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory; this.handler = handler; }
corePoolSize 核心執行緒數,執行緒池中最小執行緒數,即使執行緒空閒,也不會被銷燬;任務首先提交到核心執行緒中執行。(初始化時不建立執行緒,提交任務時建立執行緒)(如果設定allowCoreThreadTimeOut為true,核心執行緒也會被銷燬,使用較少)
maximumPoolSize 執行緒池中允許建立的最大執行緒數。
keepAliveTime 當執行緒數大於corePoolSize時,執行緒最多等待keepAliveTime時間後,將被銷燬。
unit keepAliveTime引數的時間單位,一般為毫秒。
workQueue 提交任務的快取佇列。
threadFactory 建立執行緒的工廠。
handler 當corePoolSize已滿,快取佇列已滿,maximumPoolSize已滿時,又發生任務提交時的處理器。
提交任務時: 如果執行緒數小於核心執行緒數(corePoolSize)(或者核心執行緒有空閒),則新建立執行緒(或者使用空閒執行緒)執行任務; 如果執行緒數等於核心執行緒數,則將任務快取到佇列(workQueue); 如果快取佇列已滿,則繼續建立執行緒執行任務,直到達到最大執行緒數; 如果執行緒數達到最大執行緒數(maximumPoolSize),再提交任務,將使用handler來處理無法處理的任務。