某些情況下,我們需要在項目中對多種任務分配不同的線程池進行執行。從而通過監控不同的線程池來控制不同的任務。為了達到這個目的,需要在項目中配置多線程池。
spring boot 提供了簡單高效的線程池配置和使用方案。
配置
首先是配置線程池的bean交給spring 管理:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
@configuration public class taskexecutepool { @bean (name = "threadpoola" ) public threadpooltaskexecutormytaskasyncpool() { threadpooltaskexecutor executor = new threadpooltaskexecutor(); executor.setcorepoolsize( 4 ); executor.setmaxpoolsize( 8 ); executor.setqueuecapacity( 100 ); executor.setkeepaliveseconds( 60 ); executor.setthreadnameprefix( "pool-a" ); executor.setrejectedexecutionhandler( new threadpoolexecutor.callerrunspolicy()); executor.initialize(); return executor; } @bean (name = "threadpoolb" ) public threadpooltaskexecutorasyncpoolb() { threadpooltaskexecutor executor = new threadpooltaskexecutor(); executor.setcorepoolsize( 2 ); executor.setmaxpoolsize( 4 ); executor.setqueuecapacity( 8 ); executor.setkeepaliveseconds( 60 ); executor.setthreadnameprefix( "pool-b" ); //當任務數量超過maxpoolsize和queuecapacity時使用的策略,該策略是又調用任務的線程執行 executor.setrejectedexecutionhandler( new threadpoolexecutor.callerrunspolicy()); executor.initialize(); return executor; } } |
使用
使用線程只需要在執行方法上加上注釋,同時該方法的類必須被定義為bean,交由spring管理。
可以在類上使用注解@component、@service等
1
2
3
4
|
@async (value= "threadpoola" ) public void taska(){ ... } |
查看線程活躍數:
1
2
3
4
5
6
|
@autowired private threadpooltaskexecutor threadpoola; //變量名稱為定義的線程池bean定義的name屬性名。 public void checkavtivethreadnum() { int num = threadpoola.getactivecount(); } |
當然還有其他一些方法,這里不再舉例。
線程池各屬性理解:
corepoolsize:表示線程池核心線程,正常情況下開啟的線程數量。
queuecapacity:當核心線程都在跑任務,還有多余的任務會存到此處。
maxpoolsize:如果queuecapacity存滿了,還有任務就會啟動更多的線程,直到線程數達到maxpoolsize。如果還有任務,則根據拒絕策略進行處理。
拒絕策略有多種:
- 由任務調用線程執行
- 拋異常
- 多余的直接拋棄
- 根據fifo(先進先出)拋棄隊列里任務
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.jianshu.com/p/0170d71dc502