四種Java線程池用法解析

本文爲你們分析四種Java線程池用法,供你們參考,具體內容以下java

http://www.jb51.net/article/81843.htm數據庫

一、new Thread的弊端緩存

執行一個異步任務你還只是以下new Thread嗎?安全

?
1
2
3
4
5
6
7
8
new Thread( new Runnable() {
 
   @Override
   public void run() {
     // TODO Auto-generated method stub
     }
   }
).start();

那你就out太多了,new Thread的弊端以下:服務器

a. 每次new Thread新建對象性能差。
b. 線程缺少統一管理,可能無限制新建線程,相互之間競爭,及可能佔用過多系統資源致使死機或oom。
c. 缺少更多功能,如定時執行、按期執行、線程中斷。併發

相比new Thread,Java提供的四種線程池的好處在於:app

a. 重用存在的線程,減小對象建立、消亡的開銷,性能佳。
b. 可有效控制最大併發線程數,提升系統資源的使用率,同時避免過多資源競爭,避免堵塞。
c. 提供定時執行、按期執行、單線程、併發數控制等功能。異步

二、Java 線程池ide

Java經過Executors提供四種線程池,分別爲:工具

newCachedThreadPool建立一個可緩存線程池,若是線程池長度超過處理須要,可靈活回收空閒線程,若無可回收,則新建線程。
newFixedThreadPool 建立一個定長線程池,可控制線程最大併發數,超出的線程會在隊列中等待。
newScheduledThreadPool 建立一個定長線程池,支持定時及週期性任務執行。
newSingleThreadExecutor 建立一個單線程化的線程池,它只會用惟一的工做線程來執行任務,保證全部任務按照指定順序(FIFO, LIFO, 優先級)執行。
(1)newCachedThreadPool:

建立一個可緩存線程池,若是線程池長度超過處理須要,可靈活回收空閒線程,若無可回收,則新建線程。示例代碼以下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
18
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、固定大小的線程池,newFixedThreadPool:

 

?
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
package app.executors;
 
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
 
/**
  * Java線程:線程池
  *
  * @author xiho
  */
public class Test {
   public static void main(String[] args) {
     // 建立一個可重用固定線程數的線程池
     ExecutorService pool = Executors.newFixedThreadPool( 2 );
     // 建立線程
     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();
   }
}
 
class MyThread extends Thread {
   @Override
   public void run() {
     System.out.println(Thread.currentThread().getName() + "正在執行。。。" );
   }
}

輸出結果:

?
1
2
3
4
5
pool- 1 -thread- 1 正在執行。。。
pool- 1 -thread- 3 正在執行。。。
pool- 1 -thread- 4 正在執行。。。
pool- 1 -thread- 2 正在執行。。。
pool- 1 -thread- 5 正在執行。。。

改變ExecutorService pool = Executors.newFixedThreadPool(5)中的參數:ExecutorService pool = Executors.newFixedThreadPool(2),輸出結果是:

?
1
2
3
4
5
pool- 1 -thread- 1 正在執行。。。
pool- 1 -thread- 1 正在執行。。。
pool- 1 -thread- 2 正在執行。。。
pool- 1 -thread- 1 正在執行。。。
pool- 1 -thread- 2 正在執行。。。

從以上結果能夠看出,newFixedThreadPool的參數指定了能夠運行的線程的最大數目,超過這個數目的線程加進去之後,不會運行。其次,加入線程池的線程屬於託管狀態,線程的運行不受加入順序的影響。

2、單任務線程池,newSingleThreadExecutor:

僅僅是把上述代碼中的ExecutorService pool = Executors.newFixedThreadPool(2)改成ExecutorService pool = Executors.newSingleThreadExecutor();
輸出結果:

?
1
2
3
4
5
pool- 1 -thread- 1 正在執行。。。
pool- 1 -thread- 1 正在執行。。。
pool- 1 -thread- 1 正在執行。。。
pool- 1 -thread- 1 正在執行。。。
pool- 1 -thread- 1 正在執行。。。

能夠看出,每次調用execute方法,其實最後都是調用了thread-1的run方法。

3、可變尺寸的線程池,newCachedThreadPool:

與上面的相似,只是改動下pool的建立方式:ExecutorService pool = Executors.newCachedThreadPool();

輸出結果:

?
1
2
3
4
5
pool- 1 -thread- 1 正在執行。。。
pool- 1 -thread- 2 正在執行。。。
pool- 1 -thread- 4 正在執行。。。
pool- 1 -thread- 3 正在執行。。。
pool- 1 -thread- 5 正在執行。。。

這種方式的特色是:可根據須要建立新線程的線程池,可是在之前構造的線程可用時將重用它們。

4、延遲鏈接池,newScheduledThreadPool:

 

?
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
public class TestScheduledThreadPoolExecutor {
 
   public static void 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);
 
   }
 
}

輸出結果:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
================
 
8384644549516
 
8386643829034
 
8388643830710
 
================
 
8390643851383
 
8392643879319
 
8400643939383

以上就是本文的所有內容,但願對你們的學習有所幫助。

相關文章
相關標籤/搜索