之前創建線程的時候都是用的 newCachedThreadPoo,newFixedThreadPool,newScheduledThreadPool,newSingleThreadExecutor 這四個方法。
當然 Executors 也是用不同的參數去 new ThreadPoolExecutor 實現的,本文先分析前四種線程創建方式,后在分析 new ThreadPoolExecutor 創建方式
使用 Executors 創建線程池
1.newFixedThreadPool()
由于使用了LinkedBlockingQueue所以maximumPoolSize沒用,當corePoolSize滿了之后就加入到LinkedBlockingQueue隊列中。
每當某個線程執行完成之后就從LinkedBlockingQueue隊列中取一個。
所以這個是創建固定大小的線程池。
源碼分析
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(
nThreads,
nThreads,
0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
2.newSingleThreadPool()
創建線程數為1的線程池,由于使用了LinkedBlockingQueue所以maximumPoolSize 沒用,corePoolSize為1表示線程數大小為1,滿了就放入隊列中,執行完了就從隊列取一個。
源碼分析
public static ExecutorService newSingleThreadExecutor() {
return new Executors.FinalizableDelegatedExecutorService
(
new ThreadPoolExecutor(
1,
1,
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);
}
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 核心線程數大小,當線程數 < corePoolSize ,會創建線程執行 runnable
2、maximumPoolSize 最大線程數, 當線程數 >= corePoolSize的時候,會把 runnable 放入 workQueue中
3、keepAliveTime 保持存活時間,當線程數大于corePoolSize的空閑線程能保持的最大時間。
4、unit 時間單位
5、workQueue 保存任務的阻塞隊列
6、threadFactory 創建線程的工廠
7、handler 拒絕策略
任務執行順序
1、當線程數小于 corePoolSize時,創建線程執行任務。
2、當線程數大于等于 corePoolSize并且 workQueue 沒有滿時,放入workQueue中
3、線程數大于等于 corePoolSize并且當 workQueue 滿時,新任務新建線程運行,線程總數要小于 maximumPoolSize
4、當線程總數等于 maximumPoolSize 并且 workQueue 滿了的時候執行 handler 的 rejectedExecution。也就是拒絕策略。
四個拒絕策略
ThreadPoolExecutor默認有四個拒絕策略:
1、ThreadPoolExecutor.AbortPolicy() 直接拋出異常RejectedExecutionException
2、ThreadPoolExecutor.CallerRunsPolicy() 直接調用run方法并且阻塞執行
3、ThreadPoolExecutor.DiscardPolicy() 直接丟棄后來的任務
4、ThreadPoolExecutor.DiscardOldestPolicy() 丟棄在隊列中隊首的任務
當然可以自己繼承RejectedExecutionHandler來寫拒絕策略.
TestThreadPoolExecutor 示例
TestThreadPoolExecutor.java
package io.ymq.thread.TestThreadPoolExecutor;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 描述:
*
* @author yanpenglei
* @create 2017-10-12 15:39
**/
public class TestThreadPoolExecutor {
public static void main(String[] args) {
long currentTimeMillis = System.currentTimeMillis();
// 構造一個線程池
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 6, 3,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3)
);
for (int i = 1; i <= 10; i++) {
try {
String task = "task=" + i;
System.out.println("創建任務并提交到線程池中:" + task);
threadPool.execute(new ThreadPoolTask(task));
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
//等待所有線程執行完畢當前任務。
threadPool.shutdown();
boolean loop = true;
do {
//等待所有線程執行完畢當前任務結束
loop = !threadPool.awaitTermination(2, TimeUnit.SECONDS);//等待2秒
} while (loop);
if (loop != true) {
System.out.println("所有線程執行完畢");
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("耗時:" + (System.currentTimeMillis() - currentTimeMillis));
}
}
}
ThreadPoolTask.java
package io.ymq.thread.TestThreadPoolExecutor;
import java.io.Serializable;
/**
* 描述:
*
* @author yanpenglei
* @create 2017-10-12 15:40
**/
public class ThreadPoolTask implements Runnable, Serializable {
private Object attachData;
ThreadPoolTask(Object tasks) {
this.attachData = tasks;
}
public void run() {
try {
System.out.println("開始執行任務:" + attachData + "任務,使用的線程池,線程名稱:" + Thread.currentThread().getName());
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
attachData = null;
}
}
遇到java.util.concurrent.RejectedExecutionException
第一
你的線程池 ThreadPoolExecutor 顯示的 shutdown() 之后,再向線程池提交任務的時候。 如果你配置的拒絕策略是 AbortPolicy 的話,這個異常就會拋出來。
第二
當你設置的任務緩存隊列過小的時候,或者說, 你的線程池里面所有的線程都在干活(線程數== maxPoolSize),并且你的任務緩存隊列也已經充滿了等待的隊列, 這個時候,你再向它提交任務,則會拋出這個異常。
響應
可以看到線程 pool-1-thread-1 到5 循環使用
創建任務并提交到線程池中:task=1
開始執行任務:task=1任務,使用的線程池,線程名稱:pool-1-thread-1
創建任務并提交到線程池中:task=2
開始執行任務:task=2任務,使用的線程池,線程名稱:pool-1-thread-2
創建任務并提交到線程池中:task=3
開始執行任務:task=3任務,使用的線程池,線程名稱:pool-1-thread-3
創建任務并提交到線程池中:task=4
開始執行任務:task=4任務,使用的線程池,線程名稱:pool-1-thread-4
創建任務并提交到線程池中:task=5
開始執行任務:task=5任務,使用的線程池,線程名稱:pool-1-thread-5
創建任務并提交到線程池中:task=6
開始執行任務:task=6任務,使用的線程池,線程名稱:pool-1-thread-1
創建任務并提交到線程池中:task=7
開始執行任務:task=7任務,使用的線程池,線程名稱:pool-1-thread-2
創建任務并提交到線程池中:task=8
開始執行任務:task=8任務,使用的線程池,線程名稱:pool-1-thread-3
創建任務并提交到線程池中:task=9
開始執行任務:task=9任務,使用的線程池,線程名稱:pool-1-thread-4
創建任務并提交到線程池中:task=10
開始執行任務:task=10任務,使用的線程池,線程名稱:pool-1-thread-5
所有線程執行完畢
耗時:1015