new Thread弊端如下:
每次new Thread新建對象性能差
線程缺乏統一管理,可能無限制新建線程,相互之間競爭,即可能占用過多的系統資源導致死機
缺乏更多功能,比如定時執行,定期執行,線程中斷。
java提供的四種線程池好處如下:
重用存下的線程,減少對象創建,銷毀的開銷,性能佳
可有效控制線程最大並發數,提高系統資源的使用率,同時避免資源過度競爭,避免堵塞
提供定時執行,定期執行,單線程,並發數控制等功能
四種線程池各個優勢如下
new CacheThreadPool 創建一個可緩存線程池,如果線程池長度超過需要處理,可靈活回收空閑線程,若無可回收,則創建新線程。
new FixedThreadPool 創建一個定長線程池,可控制線程最大並發數,超出的線程會在隊列里等待
new SchedluedThreadPool 創建一個定長線程池,支持定時及周期性任務執行。
new SingleTheadExcutor 創建一個單線程化的線程池,它只會為唯一的工作線程來執行任務,保證所有任務按指定順序執行
(1). newCachedThreadPool
創建一個可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則新建線程。示例代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
final int index = i;
try {
Thread.sleep(index * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
cachedThreadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(index);
}
});
}
|
線程池為無限大,當執行第二個任務時第一個任務已經完成,會復用執行第一個任務的線程,而不用每次新建線程。
(2). newFixedThreadPool
創建一個定長線程池,可控制線程最大並發數,超出的線程會在隊列中等待。示例代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
final int index = i;
fixedThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
System.out.println(index);
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
|
因為線程池大小為3,每個任務輸出index后sleep 2秒,所以每兩秒打印3個數字。
定長線程池的大小最好根據系統資源進行設置。如Runtime.getRuntime().availableProcessors()。可參考PreloadDataCache。
(3) newScheduledThreadPool
創建一個定長線程池,支持定時及周期性任務執行。延遲執行示例代碼如下:
1
2
3
4
5
6
7
8
|
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
scheduledThreadPool.schedule(new Runnable() {
@Override
public void run() {
System.out.println("delay 3 seconds");
}
}, 3, TimeUnit.SECONDS);
|
表示延遲3秒執行。
定期執行示例代碼如下:
1
2
3
4
5
6
7
|
scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("delay 1 seconds, and excute every 3 seconds");
}
}, 1, 3, TimeUnit.SECONDS);
|
表示延遲1秒后每3秒執行一次。
ScheduledExecutorService比Timer更安全,功能更強大,后面會有一篇單獨進行對比。
(4)、newSingleThreadExecutor
創建一個單線程化的線程池,它只會用唯一的工作線程來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先級)執行。示例代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
final int index = i;
singleThreadExecutor.execute(new Runnable() {
@Override
public void run() {
try {
System.out.println(index);
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
|
結果依次輸出,相當於順序執行各個任務。
現行大多數GUI程序都是單線程的。Android中單線程可用於數據庫操作,文件操作,應用批量安裝,應用批量刪除等不適合並發但可能IO阻塞性及影響UI線程響應的操作。
線程池的作用:
線程池作用就是限制系統中執行線程的數量。
根 據系統的環境情況,可以自動或手動設置線程數量,達到運行的最佳效果;少了浪費了系統資源,多了造成系統擁擠效率不高。用線程池控制線程數量,其他線程排 隊等候。一個任務執行完畢,再從隊列的中取最前面的任務開始執行。若隊列中沒有等待進程,線程池的這一資源處於等待。當一個新任務需要運行時,如果線程池 中有等待的工作線程,就可以開始運行了;否則進入等待隊列。
為什么要用線程池:
1.減少了創建和銷毀線程的次數,每個工作線程都可以被重復利用,可執行多個任務。
2.可以根據系統的承受能力,調整線程池中工作線線程的數目,防止因為消耗過多的內存,而把服務器累趴下(每個線程需要大約1MB內存,線程開的越多,消耗的內存也就越大,最后死機)。
Java里面線程池的頂級接口是Executor,但是嚴格意義上講Executor並不是一個線程池,而只是一個執行線程的工具。真正的線程池接口是ExecutorService。
比較重要的幾個類:
ExecutorService |
真正的線程池接口。 |
ScheduledExecutorService |
能和Timer/TimerTask類似,解決那些需要任務重復執行的問題。 |
ThreadPoolExecutor |
ExecutorService的默認實現。 |
ScheduledThreadPoolExecutor |
繼承ThreadPoolExecutor的ScheduledExecutorService接口實現,周期性任務調度的類實現。 |
要配置一個線程池是比較復雜的,尤其是對於線程池的原理不是很清楚的情況下,很有可能配置的線程池不是較優的,因此在Executors類里面提供了一些靜態工廠,生成一些常用的線程池。
1. newSingleThreadExecutor
創建一個單線程的線程池。這個線程池只有一個線程在工作,也就是相當於單線程串行執行所有任務。如果這個唯一的線程因為異常結束,那么會有一個新的線程來替代它。此線程池保證所有任務的執行順序按照任務的提交順序執行。
2.newFixedThreadPool
創建固定大小的線程池。每次提交一個任務就創建一個線程,直到線程達到線程池的最大大小。線程池的大小一旦達到最大值就會保持不變,如果某個線程因為執行異常而結束,那么線程池會補充一個新線程。
3. newCachedThreadPool
創建一個可緩存的線程池。如果線程池的大小超過了處理任務所需要的線程,
那么就會回收部分空閑(60秒不執行任務)的線程,當任務數增加時,此線程池又可以智能的添加新線程來處理任務。此線程池不會對線程池大小做限制,線程池大小完全依賴於操作系統(或者說JVM)能夠創建的最大線程大小。
4.newScheduledThreadPool
創建一個大小無限的線程池。此線程池支持定時以及周期性執行任務的需求。
實例
1:newSingleThreadExecutor
MyThread.java
publicclassMyThread extends Thread { @Override publicvoid run() { System.out.println(Thread.currentThread().getName() + "正在執行。。。"); } } |
TestSingleThreadExecutor.java
publicclassTestSingleThreadExecutor { publicstaticvoid main(String[] args) { //創建一個可重用固定線程數的線程池 ExecutorService pool = Executors. newSingleThreadExecutor(); //創建實現了Runnable接口對象,Thread對象當然也實現了Runnable接口 Thread t1 = new MyThread(); Thread t2 = new MyThread(); Thread t3 = new MyThread(); Thread t4 = new MyThread(); Thread t5 = new MyThread(); //將線程放入池中進行執行 pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); //關閉線程池 pool.shutdown(); } } |
輸出結果
pool-1-thread-1正在執行。。。 pool-1-thread-1正在執行。。。 pool-1-thread-1正在執行。。。 pool-1-thread-1正在執行。。。 pool-1-thread-1正在執行。。。 |
2newFixedThreadPool
TestFixedThreadPool.Java
publicclass TestFixedThreadPool { publicstaticvoid main(String[] args) { //創建一個可重用固定線程數的線程池 ExecutorService pool = Executors.newFixedThreadPool(2); //創建實現了Runnable接口對象,Thread對象當然也實現了Runnable接口 Thread t1 = new MyThread(); Thread t2 = new MyThread(); Thread t3 = new MyThread(); Thread t4 = new MyThread(); Thread t5 = new MyThread(); //將線程放入池中進行執行 pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); //關閉線程池 pool.shutdown(); } } |
輸出結果
pool-1-thread-1正在執行。。。 pool-1-thread-2正在執行。。。 pool-1-thread-1正在執行。。。 pool-1-thread-2正在執行。。。 pool-1-thread-1正在執行。。。 |
3 newCachedThreadPool
TestCachedThreadPool.java
publicclass TestCachedThreadPool { publicstaticvoid main(String[] args) { //創建一個可重用固定線程數的線程池 ExecutorService pool = Executors.newCachedThreadPool(); //創建實現了Runnable接口對象,Thread對象當然也實現了Runnable接口 Thread t1 = new MyThread(); Thread t2 = new MyThread(); Thread t3 = new MyThread(); Thread t4 = new MyThread(); Thread t5 = new MyThread(); //將線程放入池中進行執行 pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); //關閉線程池 pool.shutdown(); } } |
輸出結果:
pool-1-thread-2正在執行。。。 pool-1-thread-4正在執行。。。 pool-1-thread-3正在執行。。。 pool-1-thread-1正在執行。。。 pool-1-thread-5正在執行。。。 |
4newScheduledThreadPool
TestScheduledThreadPoolExecutor.java
publicclass TestScheduledThreadPoolExecutor { publicstaticvoid main(String[] args) { ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1); exec.scheduleAtFixedRate(new Runnable() {//每隔一段時間就觸發異常 @Override publicvoid run() { //throw new RuntimeException(); System.out.println("================"); } }, 1000, 5000, TimeUnit.MILLISECONDS); exec.scheduleAtFixedRate(new Runnable() {//每隔一段時間打印系統時間,證明兩者是互不影響的 @Override publicvoid run() { System.out.println(System.nanoTime()); } }, 1000, 2000, TimeUnit.MILLISECONDS); } } |
輸出結果
================ 8384644549516 8386643829034 8388643830710 ================ 8390643851383 8392643879319 8400643939383 |