本文引領大家進入線程池的世界
很多人對線程的認識可能比較熟悉, 知道它能開啟一個任務去做某些事情, 那么線程池又是什么鬼? 不著急, 我們先來回顧一下線程的使用.
Java 線程
正常情況下我們使用線程都是用new Thread()
來開啟一個線程:
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
}
}).start();
我們先來看看 new Thread()
的弊端:
- 每次
new Thread()
都會新建對象導致性能差。 - 線程缺乏統一管理,可能無限制新建線程,相互之間競爭,及可能占用過多系統資源導致死機或oom。
- 缺乏更多功能,如定時執行、定期執行、線程中斷。
執行一個異步任務你還只是如上
new Thread()
嗎? 那你就out太多了,是時候了解Java線程池的使用了~
Java 線程池
顧名思義, 線程池就是用來管理線程的池子, Java通過Executors提供四種線程池,分別為:
- newCachedThreadPool創建一個可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則新建線程。
- newFixedThreadPool 創建一個定長線程池,可控制線程最大并發數,超出的線程會在隊列中等待。
- newScheduledThreadPool 創建一個定長線程池,支持定時及周期性任務執行。
- newSingleThreadExecutor 創建一個單線程化的線程池,它只會用唯一的工作線程來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先級)執行。
相比new Thread()
,Java提供的線程池的好處在于:
- 重用存在的線程,減少對象創建、消亡的開銷,性能更佳。
- 可有效控制最大并發線程數,提高系統資源的使用率,同時避免過多資源競爭,避免堵塞。
- 提供定時執行、定期執行、單線程、并發數控制等功能。
理論永遠不如實踐來的實在, 那么我們舉栗子說明
首先我們來看看Thread 的用法:
public class ThreadTest {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
final int index = i;
try {
Thread.sleep(index * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getId() + "");
}
}).start();;
}
}
}
//輸出結果
11
12
13
14
15
16
17
18
19
20
可以看出創建了10個不同的線程, 如果后臺任務頻繁, 系統哪有那么多資源給你用?
接下來我們來看看線程池是怎么工作的吧..
1. newCachedThreadPool
創建一個可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則新建線程。示例代碼如下:
public class CachedTheardPoolTest {
public static void main(String[] args) {
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
final int index = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
cachedThreadPool.execute(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getId() + "");
}
});
}
}
}
//輸出結果
11
11
11
11
11
11
11
11
11
11
線程池為無限大,當執行第二個任務時第一個任務已經完成,會復用執行第一個任務的線程,而不用每次新建線程。
2. newFixedThreadPool
創建一個定長線程池,可控制線程最大并發數,超出的線程會在隊列中等待。示例代碼如下:
public class FixedThreadPoolTest {
public static void main(String[] args) {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
final int index = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
fixedThreadPool.execute(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getId() + "");
}
});
}
}
}
//輸出結果
11
12
13
11
12
13
11
12
13
11
因為線程池大小為3,所以只創建三個可用線程,超出的等待之前任務完成后才執行.
定長線程池的大小最好根據系統資源進行設置。如Runtime.getRuntime().availableProcessors()。
3. newScheduledThreadPool
創建一個定長線程池,支持定時及周期性任務執行。延遲執行示例代碼如下:
public class ScheduledThreadPoolTest {
public static void main(String[] args) {
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
//延遲三秒執行
scheduledThreadPool.schedule(new Runnable() {
public void run() {
System.out.println("delay 3 seconds");
}
}, 3, TimeUnit.SECONDS);
//延遲1秒后每3秒執行一次
scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println("delay 1 seconds, and excute every 3 seconds");
}
}, 1, 3, TimeUnit.SECONDS);
}
}
//輸出結果
delay 1 seconds, and excute every 3 seconds
11
delay 3 seconds
12
delay 1 seconds, and excute every 3 seconds
11
delay 1 seconds, and excute every 3 seconds
11
delay 1 seconds, and excute every 3 seconds
11
delay 1 seconds, and excute every 3 seconds
14
delay 1 seconds, and excute every 3 seconds
12
delay 1 seconds, and excute every 3 seconds
12
delay 1 seconds, and excute every 3 seconds
14
delay 1 seconds, and excute every 3 seconds
14
delay 1 seconds, and excute every 3 seconds
14
delay 1 seconds, and excute every 3 seconds
14
delay 1 seconds, and excute every 3 seconds
14
delay 1 seconds, and excute every 3 seconds
14
ScheduledExecutorService
比 Timer
更安全,功能更強大哦.
4. newSingleThreadExecutor
創建一個單線程化的線程池,它只會用唯一的工作線程來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先級)執行。示例代碼如下:
public class SingleThreadExecutorTest {
public static void main(String[] args) {
ExecutorService singleThreadExecutor = Executors
.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
singleThreadExecutor.execute(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getId() + "");
}
});
}
}
}
//輸出結果
11
11
11
11
11
11
11
11
11
11
結果依次輸出,相當于順序執行各個任務。
現行大多數GUI程序都是單線程的。適用于IO操作,不阻塞主線程.
順便期待簡書可以上傳文件~
好啦~~ 對Java線程池的概念大家也了解的差不多了, 希望對大家的學習有所幫助~~~
最后, 提醒大家,千萬別看完就忘了哦, 要學以致用!