一. 線程池簡介
1. 線程池的概念:
線程池就是首先創建一些線程,它們的集合稱為線程池。使用線程池可以很好地提高性能,線程池在系統啟動時即創建大量空閑的線程,程序將一個任務傳給線程池,線程池就會啟動一條線程來執行這個任務,執行結束以后,該線程并不會死亡,而是再次返回線程池中成為空閑狀態,等待執行下一個任務。
2. 線程池的工作機制
2.1 在線程池的編程模式下,任務是提交給整個線程池,而不是直接提交給某個線程,線程池在拿到任務后,就在內部尋找是否有空閑的線程,如果有,則將任務交給某個空閑的線程。
2.2 一個線程同時只能執行一個任務,但可以同時向一個線程池提交多個任務。
3. 使用線程池的原因:
多線程運行時間,系統不斷的啟動和關閉新線程,成本非常高,會過渡消耗系統資源,以及過渡切換線程的危險,從而可能導致系統資源的崩潰。這時,線程池就是最好的選擇了。
二. 四種常見的線程池詳解
1. 線程池的返回值executorservice簡介:
executorservice
是java提供的用于管理線程池的類。該類的兩個作用:控制線程數量和重用線程
2. 具體的4種常用的線程池實現如下:(返回值都是executorservice)
2.1 executors.newcachethreadpool()
:可緩存線程池,先查看池中有沒有以前建立的線程,如果有,就直接使用。如果沒有,就建一個新的線程加入池中,緩存型池子通常用于執行一些生存期很短的異步型任務
示例代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package com.study.test; import java.util.concurrent.executorservice; import java.util.concurrent.executors; public class threadpoolexecutortest { public static void main(string[] args) { //創建一個可緩存線程池 executorservice cachedthreadpool = executors.newcachedthreadpool(); for ( int i = 0 ; i < 10 ; i++) { try { //sleep可明顯看到使用的是線程池里面以前的線程,沒有創建新的線程 thread.sleep( 1000 ); } catch (interruptedexception e) { e.printstacktrace(); } cachedthreadpool.execute( new runnable() { public void run() { //打印正在執行的緩存線程信息 system.out.println(thread.currentthread().getname()+ "正在被執行" ); } }); } } } |
輸出結果:
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
pool-1-thread-1正在被執行
線程池為無限大,當執行當前任務時上一個任務已經完成,會復用執行上一個任務的線程,而不用每次新建線程
2.2 executors.newfixedthreadpool(int n)
:創建一個可重用固定個數的線程池,以共享的無界隊列方式來運行這些線程。
示例代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
package com.study.test; import java.util.concurrent.executorservice; import java.util.concurrent.executors; public class threadpoolexecutortest { public static void main(string[] args) { //創建一個可重用固定個數的線程池 executorservice fixedthreadpool = executors.newfixedthreadpool( 3 ); for ( int i = 0 ; i < 10 ; i++) { fixedthreadpool.execute( new runnable() { public void run() { try { //打印正在執行的緩存線程信息 system.out.println(thread.currentthread().getname()+ "正在被執行" ); thread.sleep( 2000 ); } catch (interruptedexception e) { e.printstacktrace(); } } }); } } } |
輸出結果:
pool-1-thread-1正在被執行
pool-1-thread-2正在被執行
pool-1-thread-3正在被執行
pool-1-thread-1正在被執行
pool-1-thread-2正在被執行
pool-1-thread-3正在被執行
pool-1-thread-1正在被執行
pool-1-thread-2正在被執行
pool-1-thread-3正在被執行
pool-1-thread-1正在被執行
因為線程池大小為3,每個任務輸出打印結果后sleep 2秒,所以每兩秒打印3個結果。
定長線程池的大小最好根據系統資源進行設置。如runtime.getruntime().availableprocessors()
2.3 executors.newscheduledthreadpool(int n)
:創建一個定長線程池,支持定時及周期性任務執行
延遲執行示例代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
package com.study.test; import java.util.concurrent.executors; import java.util.concurrent.scheduledexecutorservice; import java.util.concurrent.timeunit; public class threadpoolexecutortest { public static void main(string[] args) { //創建一個定長線程池,支持定時及周期性任務執行——延遲執行 scheduledexecutorservice scheduledthreadpool = executors.newscheduledthreadpool( 5 ); //延遲1秒執行 scheduledthreadpool.schedule( new runnable() { public void run() { system.out.println( "延遲1秒執行" ); } }, 1 , timeunit.seconds); } } |
輸出結果:
延遲1秒執行
定期執行示例代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
package com.study.test; import java.util.concurrent.executors; import java.util.concurrent.scheduledexecutorservice; import java.util.concurrent.timeunit; public class threadpoolexecutortest { public static void main(string[] args) { //創建一個定長線程池,支持定時及周期性任務執行——定期執行 scheduledexecutorservice scheduledthreadpool = executors.newscheduledthreadpool( 5 ); //延遲1秒后每3秒執行一次 scheduledthreadpool.scheduleatfixedrate( new runnable() { public void run() { system.out.println( "延遲1秒后每3秒執行一次" ); } }, 1 , 3 , timeunit.seconds); } } |
輸出結果:
延遲1秒后每3秒執行一次
延遲1秒后每3秒執行一次
.............
2.4 executors.newsinglethreadexecutor()
:創建一個單線程化的線程池,它只會用唯一的工作線程來執行任務,保證所有任務按照指定順序(fifo, lifo, 優先級)執行。
示例代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package com.study.test; import java.util.concurrent.executorservice; import java.util.concurrent.executors; public class testthreadpoolexecutor { public static void main(string[] args) { //創建一個單線程化的線程池 executorservice singlethreadexecutor = executors.newsinglethreadexecutor(); for ( int i = 0 ; i < 10 ; i++) { final int index = i; singlethreadexecutor.execute( new runnable() { public void run() { try { //結果依次輸出,相當于順序執行各個任務 system.out.println(thread.currentthread().getname()+ "正在被執行,打印的值是:" +index); thread.sleep( 1000 ); } catch (interruptedexception e) { e.printstacktrace(); } } }); } } } |
輸出結果:
pool-1-thread-1正在被執行,打印的值是:0
pool-1-thread-1正在被執行,打印的值是:1
pool-1-thread-1正在被執行,打印的值是:2
pool-1-thread-1正在被執行,打印的值是:3
pool-1-thread-1正在被執行,打印的值是:4
pool-1-thread-1正在被執行,打印的值是:5
pool-1-thread-1正在被執行,打印的值是:6
pool-1-thread-1正在被執行,打印的值是:7
pool-1-thread-1正在被執行,打印的值是:8
pool-1-thread-1正在被執行,打印的值是:9
三. 緩沖隊列blockingqueue和自定義線程池threadpoolexecutor
1. 緩沖隊列blockingqueue簡介:
blockingqueue是雙緩沖隊列。blockingqueue內部使用兩條隊列,允許兩個線程同時向隊列一個存儲,一個取出操作。在保證并發安全的同時,提高了隊列的存取效率。
2. 常用的幾種blockingqueue:
- arrayblockingqueue(int i):規定大小的blockingqueue,其構造必須指定大小。其所含的對象是fifo順序排序的。
- linkedblockingqueue()或者(int i):大小不固定的blockingqueue,若其構造時指定大小,生成的blockingqueue有大小限制,不指定大小,其大小有integer.max_value來決定。其所含的對象是fifo順序排序的。
- priorityblockingqueue()或者(int i):類似于linkedblockingqueue,但是其所含對象的排序不是fifo,而是依據對象的自然順序或者構造函數的comparator決定。
- synchronizedqueue():特殊的blockingqueue,對其的操作必須是放和取交替完成。
3. 自定義線程池(threadpoolexecutor和blockingqueue連用):
自定義線程池,可以用threadpoolexecutor類創建,它有多個構造方法來創建線程池。
常見的構造函數:threadpoolexecutor(int corepoolsize, int maximumpoolsize, long keepalivetime, timeunit unit, blockingqueue<runnable> workqueue)
示例代碼:
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
|
package com.study.test; import java.util.concurrent.arrayblockingqueue; import java.util.concurrent.blockingqueue; import java.util.concurrent.threadpoolexecutor; import java.util.concurrent.timeunit; class tempthread implements runnable { @override public void run() { // 打印正在執行的緩存線程信息 system.out.println(thread.currentthread().getname() + "正在被執行" ); try { // sleep一秒保證3個任務在分別在3個線程上執行 thread.sleep( 1000 ); } catch (interruptedexception e) { e.printstacktrace(); } } } public class testthreadpoolexecutor { public static void main(string[] args) { // 創建數組型緩沖等待隊列 blockingqueue<runnable> bq = new arrayblockingqueue<runnable>( 10 ); // threadpoolexecutor:創建自定義線程池,池中保存的線程數為3,允許最大的線程數為6 threadpoolexecutor tpe = new threadpoolexecutor( 3 , 6 , 50 , timeunit.milliseconds, bq); // 創建3個任務 runnable t1 = new tempthread(); runnable t2 = new tempthread(); runnable t3 = new tempthread(); // runnable t4 = new tempthread(); // runnable t5 = new tempthread(); // runnable t6 = new tempthread(); // 3個任務在分別在3個線程上執行 tpe.execute(t1); tpe.execute(t2); tpe.execute(t3); // tpe.execute(t4); // tpe.execute(t5); // tpe.execute(t6); // 關閉自定義線程池 tpe.shutdown(); } } |
輸出結果:
pool-1-thread-1正在被執行
pool-1-thread-2正在被執行
pool-1-thread-3正在被執行
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對服務器之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
原文鏈接:https://blog.csdn.net/hnd978142833/article/details/80253784