1. 為什么要使用線程池
在上一節(jié)中已經(jīng)介紹了線程的創(chuàng)建方式,當(dāng)需要并行執(zhí)行一個(gè)任務(wù)就創(chuàng)建一個(gè)線程來執(zhí)行。但是頻繁的創(chuàng)建線程以及回收線程資源,容易在jvm中造成很大的性能消耗。這時(shí)我們就會(huì)想:能不能在一個(gè)池子中創(chuàng)建線程,當(dāng)有任務(wù)來時(shí),就從池子中取出一個(gè)線程來執(zhí)行任務(wù),當(dāng)任務(wù)執(zhí)行完畢,就將線程放回池子里面,等待下一個(gè)需要執(zhí)行的任務(wù)。上帝說要有池子,于是便有了線程池。
2.線程池的創(chuàng)建以及常用的線程池
//常見的線程池創(chuàng)建都是通過調(diào)用Executors的靜態(tài)方法生成
ExecutorService pool = Executors.newCachedThreadPool();
//看下Executors的內(nèi)部靜態(tài)創(chuàng)建線程池方法
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
//再看下ThreadPoolExcutor的構(gòu)造函數(shù),初步了解下各個(gè)參數(shù)的意義,下一節(jié)會(huì)有詳解
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
long keepAliveTime,TimeUnit unit, BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
如上面所示,我們最常使用的cachedThreadPool就是通過調(diào)用Executors的靜態(tài)方法生成,它是一個(gè)可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則新建線程。具有以下特點(diǎn):
- 工作線程的創(chuàng)建數(shù)量幾乎沒有限制(其實(shí)也有限制的,數(shù)目為Interger. MAX_VALUE), 這樣可靈活的往線程池中添加線程。
- 如果長時(shí)間沒有往線程池中提交任務(wù),即如果工作線程空閑了指定的時(shí)間(默認(rèn)為1分鐘),則該工作線程將自動(dòng)終止。終止后,如果你又提交了新的任務(wù),則線程池重新創(chuàng)建一個(gè)工作線程。
- 在使用CachedThreadPool時(shí),一定要注意控制任務(wù)的數(shù)量,否則,由于大量線程同時(shí)運(yùn)行,很有會(huì)造成系統(tǒng)癱瘓。
除了CachedThreadPool,還有以下幾種常見的線程池
(1)FixedThreadPool
public static ExecutorService newFixedThreadPool
(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}
FixedThreadPool創(chuàng)建一個(gè)指定工作線程數(shù)量的線程池。每當(dāng)提交一個(gè)任務(wù)就創(chuàng)建一個(gè)工作線程,如果工作線程數(shù)量達(dá)到線程池初始的最大數(shù),則將提交的任務(wù)存入到池隊(duì)列LinkedBlockingQueue中。
FixedThreadPool是一個(gè)典型且優(yōu)秀的線程池,它具有線程池提高程序效率和節(jié)省創(chuàng)建線程時(shí)所耗的開銷的優(yōu)點(diǎn)。但是,在線程池空閑時(shí),即線程池中沒有可運(yùn)行任務(wù)時(shí),它不會(huì)釋放工作線程,還會(huì)占用一定的系統(tǒng)資源。
(2)SingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
SingleThreadExecutor創(chuàng)建一個(gè)單線程化的Executor,即只創(chuàng)建唯一的工作者線程來執(zhí)行任務(wù),它只會(huì)用唯一的工作線程來執(zhí)行任務(wù),保證所有任務(wù)按照指定順序(FIFO, LIFO, 優(yōu)先級(jí))執(zhí)行。如果這個(gè)線程異常結(jié)束,會(huì)有另一個(gè)取代它,保證順序執(zhí)行。
單工作線程最大的特點(diǎn)是可保證順序地執(zhí)行各個(gè)任務(wù),并且在任意給定的時(shí)間不會(huì)有多個(gè)線程是活動(dòng)的。
(3)ScheduledThreadPool
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
ScheduledThreadPool創(chuàng)建一個(gè)定長的線程池,而且支持定時(shí)的以及周期性的任務(wù)執(zhí)行,支持定時(shí)及周期性任務(wù)執(zhí)行。
3.使用例子
CacheThreadPool、FixedThreadPool、SingleThreadExecutor用法都是差不多的,都是將一個(gè)任務(wù)直接交給線程池execute,最終得到結(jié)果。
package com.demo.noteBook;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class CacheThreadPoolTest {
public static void main(String[] args) throws Exception {
ExecutorService cacheThreadPool = Executors.newCachedThreadPool();
//這里如果用volatile修飾int保存結(jié)果,由于累加和賦值不是原子操作,會(huì)導(dǎo)致結(jié)果出錯(cuò)
AtomicInteger sumResult = new AtomicInteger(0);
for(int k = 0; k < 10; k++){
cacheThreadPool.execute(()->{
for(int i = 1; i <= 100; i++){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
sumResult.addAndGet(i);
System.out.println("sumResult is" + sumResult) ;
}
});
}
//將線程池關(guān)閉,不再接受新任務(wù),等待線程池里面的任務(wù)執(zhí)行完成
cacheThreadPool.shutdown();
//在調(diào)用shutdown后,才會(huì)在任務(wù)都執(zhí)行完畢后,將isTerminated設(shè)置為true
while(true){
if(cacheThreadPool.isTerminated()){
System.out.println("sumResult is over" + sumResult) ;
break;
}
}
}
}
ScheduleThreadPool使用方法比較特殊,首先它不是使用ExecutorService,而是它的子類ScheduledExecutorService,它按周期執(zhí)行任務(wù)的方法不是execute,而是ScheduledExecutorService的schedule等方法,下面是一個(gè)使用的例子:
package com.demo.noteBook;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduleThreadPoolTest {
public static void main(String[] args) {
//實(shí)現(xiàn)功能,在程序運(yùn)行5s后,每隔3s say hello 一次
ScheduledExecutorService scheduleThreadPo =
Executors.newScheduledThreadPool(5);
scheduleThreadPool.scheduleAtFixedRate(new Runnable(){
public void run(){
System.out.println(" I say hello");
}
}, 5, 3, TimeUnit.SECONDS);
}
}