1. ThreadPool線程池
1.1 線程池的使用
-
線程復用、控制最大并發數、管理線程
- 降低資源消耗。通過重復利用已創建的線程降低線程創建和銷毀造成的銷耗。
- 提高響應速度。當任務到達時,任務可以不需要等待線程創建就能立即執行。
- 提高線程的可管理性。線程是稀缺資源,如果無限制的創建,不僅會銷耗系統資源,還會降低系統的穩定性,使用線程池可以進行統一的分配,調優和監控。
-
線程池架構
1608252489878.png? Executor,Executors,ExecutorService,ThreadPoolExecutor
1.1.1 三大方法
-
Executors.newFixedThreadPool(int)
- 執行長期任務性能好,創建一個線程池,一池有N個固定的線程,有固定線程數的線程
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
- newFixedThreadPool創建的線程池corePoolSize和maximumPoolSize值是相等的,它使用的是LinkedBlockingQueue
-
Executors.newSingleThreadExecutor()
- 一個任務一個任務的執行,一池一線程
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
- newSingleThreadExecutor 創建的線程池corePoolSize和maximumPoolSize值都是1,它使用的是LinkedBlockingQueue
-
Executors.newCachedThreadPool()
- 執行很多短期異步任務,線程池根據需要創建新線程,但在先前構建的線程可用時將重用它們。可擴容,遇強則強
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
- newCachedThreadPool創建的線程池將corePoolSize設置為0,將maximumPoolSize設置為Integer.MAX_VALUE,它使用的是SynchronousQueue,也就是說來了任務就創建線程運行,當線程空閑超過60秒,就銷毀線程。
從以上源碼可以看出,三大方法底層均是使用ThreadPoolExecutor()來創建線程池
代碼
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 線程池
* Arrays
* Collections
* Executors
*/
public class MyThreadPoolDemo {
public static void main(String[] args) {
//List list = new ArrayList();
//List list = Arrays.asList("a","b");
//固定數的線程池,一池五線程
//一個銀行網點,5個受理業務的窗口
//ExecutorService threadPool = Executors.newFixedThreadPool(5);
//一個銀行網點,1個受理業務的窗口
//ExecutorService threadPool = Executors.newSingleThreadExecutor();
//一個銀行網點,可擴展受理業務的窗口
ExecutorService threadPool = Executors.newCachedThreadPool();
//10個顧客請求
try {
for (int i = 1; i <=10; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t 辦理業務");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
}
}
-
工作中均不使用以上三大方法來創建線程池,而是直接使用ThreadPoolExecutor()來創建線程池
1608256649626.png
public static void main(String[] args) {
ExecutorService threadPool = new ThreadPoolExecutor(
2,
5,
2L,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(3),
Executors.defaultThreadFactory(),
//new ThreadPoolExecutor.AbortPolicy()
//new ThreadPoolExecutor.CallerRunsPolicy()
//new ThreadPoolExecutor.DiscardOldestPolicy()
new ThreadPoolExecutor.DiscardOldestPolicy()
);
//10個顧客請求
try {
for (int i = 1; i <= 10; i++) {
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + "\t 辦理業務");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
}
1.2 七大參數
- ThreadPoolExecutor()源碼
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @param threadFactory the factory to use when the executor
* creates a new thread
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code corePoolSize < 0}<br>
* {@code keepAliveTime < 0}<br>
* {@code maximumPoolSize <= 0}<br>
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue}
* or {@code threadFactory} or {@code handler} is null
*/
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:線程池中的常駐核心線程數
- maximumPoolSize:線程池中能夠容納同時執行的最大線程數,此值必須大于等于1
- keepAliveTime:多余的空閑線程的存活時間,當前池中線程數量超過corePoolSize時,當空閑時間達到keepAliveTime時,多余線程會被銷毀直到只剩下corePoolSize個線程為止
- unit:keepAliveTime的單位
- workQueue:任務隊列,被提交但尚未被執行的任務
- threadFactory:表示生成線程池中工作線程的線程工廠,用于創建線程,一般默認的即可
- handler:拒絕策略,表示當隊列滿了,并且工作線程大于等于線程池的最大線程數(maximumPoolSize)時如何來拒絕請求執行的runnable的策略
1.3 四種拒絕策略
拒絕策略:等待隊列已經排滿了,再也塞不下新任務了,同時,線程池中的max線程也達到了,無法繼續為新任務服務。這個是時候我們就需要拒絕策略機制合理的處理這個問題。
-
JDK內置四種拒絕策略
1608256190928.png
- AbortPolicy(默認):直接拋出RejectedExecutionException異常阻止系統正常運行
- CallerRunsPolicy:“調用者運行”一種調節機制,該策略既不會拋棄任務,也不會拋出異常,而是將某些任務回退到調用者,從而降低新任務的流量。
- DiscardOldestPolicy:拋棄隊列中等待最久的任務,然后把當前任務加人隊列中嘗試再次提交當前任務。
- DiscardPolicy:該策略默默地丟棄無法處理的任務,不予任何處理也不拋出異常。如果允許任務丟失,這是最好的一種策略。
/**
* new ThreadPoolExecutor.AbortPolicy() // 銀行滿了,還有人進來,不處理這個人的,拋出異常
* new ThreadPoolExecutor.CallerRunsPolicy() // 哪來的去哪里!
* new ThreadPoolExecutor.DiscardPolicy() //隊列滿了,丟掉任務,不會拋出異常!
* new ThreadPoolExecutor.DiscardOldestPolicy() //隊列滿了,嘗試去和最早的競爭,也不會拋出異常!
*/
- 以上內置拒絕策略均實現了RejectedExecutionHandle接口
1.4 線程池底層運行原理
1608262423930.png
1608262155163.png
在創建了線程池后,開始等待請求。
-
當調用execute()方法添加一個請求任務時,線程池會做出如下判斷:
- 1如果正在運行的線程數量小于corePoolSize,那么馬上創建線程運行這個任務;
- 2如果正在運行的線程數量大于或等于corePoolSize,那么將這個任務放入隊列;
- 3如果這個時候隊列滿了且正在運行的線程數量還小于maximumPoolSize,那么還是要創建非核心線程立刻運行這個任務(隊列中的依舊在等待);
- 4如果隊列滿了且正在運行的線程數量大于或等于maximumPoolSize,那么線程池會啟動飽和拒絕策略來執行。
當一個線程完成任務時,它會從隊列中取下一個任務來執行。
-
當一個線程無事可做超過一定的時間(keepAliveTime)時,線程會判斷:
- 如果當前運行的線程數大于corePoolSize,那么這個線程就被停掉。所以線程池的所有任務完成后,它最終會收縮到corePoolSize的大小。
-
舉例:
- 銀行有5個窗口(maximumPoolSize),2個啟用(corePoolSize),3個暫停服務,且等待區有5張椅子供等待使用(workQueue),開始時前面進來的2個客戶直接到啟用的2個窗口辦理業務,后面來的客戶,先到等待區椅子上等待,當等待區5張椅子坐滿后,又有人進來辦業務,于是銀行就啟用另外3個窗口進行服務,辦理完業務的窗口,直接喊等待區的人去那個窗口辦理,當5個窗口都在服務,且等待區也滿的時候,銀行只能讓保安在門口堵著(RejectedExecutionHandler),拒絕后面的人員進入(畢竟疫情期間不能擠在一起嘛!!!)
import java.util.concurrent.*; /** * @Description TODO * @Package: juc.juc * @ClassName ThreadPoolDemo * @author: wuwb * @date: 2020/12/18 9:12 */ public class ThreadPoolDemo { public static void main(String[] args) { ExecutorService threadPool = new ThreadPoolExecutor( 2, 5, 2L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy() ); try { for (int i = 1; i <= 10; i++) { final int j = i; threadPool.execute(()->{ System.out.println(Thread.currentThread().getName() + " run " + j); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } }); } } catch (Exception e) { e.printStackTrace(); } finally { threadPool.shutdown(); } } } /* pool-1-thread-1 run 1 pool-1-thread-2 run 2 pool-1-thread-3 run 8 pool-1-thread-4 run 9 pool-1-thread-5 run 10 pool-1-thread-1 run 3 pool-1-thread-4 run 4 pool-1-thread-2 run 5 pool-1-thread-3 run 6 pool-1-thread-5 run 7 1、2進核心線程,3、4、5、6、7進隊列等待,8、9、10啟用非核心線程先于隊列中任務運行 */
*CPU密集型 最大線程數為CPU核數,CPU核數Runtime.getRuntime().availableProcessors();