一、簡介
- 什么是線程池?
池的概念大家也許都有所聽聞丁存,池就是相當于一個容器肩杈,里面有許許多多的東西你可以即拿即用。java中有線程池解寝、連接池等等扩然。線程池就是在系統(tǒng)啟動或者實例化池時創(chuàng)建一些空閑的線程,等待工作調(diào)度聋伦,執(zhí)行完任務(wù)后夫偶,線程并不會立即被銷毀,而是重新處于空閑狀態(tài)觉增,等待下一次調(diào)度索守。
- 線程池的工作機制?
在線程池的編程模式中抑片,任務(wù)提交并不是直接提交給線程卵佛,而是提交給池。線程池在拿到任務(wù)之后敞斋,就會尋找有沒有空閑的線程截汪,有則分配給空閑線程執(zhí)行,暫時沒有則會進入等待隊列植捎,繼續(xù)等待空閑線程衙解。如果超出最大接受的工作數(shù)量,則會觸發(fā)線程池的拒絕策略焰枢。
- 為什么使用線程池蚓峦?
線程的創(chuàng)建與銷毀需要消耗大量資源,重復(fù)的創(chuàng)建與銷毀明顯不必要济锄。而且池的好處就是響應(yīng)快暑椰,需要的時候自取,就不會存在等待創(chuàng)建的時間荐绝。線程池可以很好地管理系統(tǒng)內(nèi)部的線程一汽,如數(shù)量以及調(diào)度。
二低滩、常用線程池介紹
Java類ExecutorService是線程池的父接口召夹,并非頂層接口。以下四種常用線程池的類型都可以是ExecutorService恕沫。
- 單一線程池 Executors.newSingleThreadExecutor()
內(nèi)部只有唯一一個線程進行工作調(diào)度监憎,可以保證任務(wù)的執(zhí)行順序(FIFO,LIFO)
package com.test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class PoolTest {
public static void main(String[] args) {
// 創(chuàng)建單一線程池
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
List<String> list = new ArrayList<String>();
list.add("first");
list.add("second");
list.add("third");
list.forEach(o -> {
// 遍歷集合提交任務(wù)
singleThreadExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " : " + o);
try {
// 間隔1s
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
});
}
}
執(zhí)行結(jié)果:
pool-1-thread-1 : first
pool-1-thread-1 : second
pool-1-thread-1 : third
- 可緩存線程池 Executors.newCachedThreadPool()
如果線程池中有可使用的線程,則使用婶溯,如果沒有鲸阔,則在池中新建一個線程偷霉,可緩存線程池中線程數(shù)量最大為Integer.MAX_VALUE。通常用它來運行一些執(zhí)行時間短隶债,且經(jīng)常用到的任務(wù)。
package com.test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class PoolTest {
public static void main(String[] args) {
// 創(chuàng)建可緩存線程池
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
List<String> list = new ArrayList<String>();
list.add("first");
list.add("second");
list.add("third");
list.forEach(o -> {
try {
// 間隔3s
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 遍歷集合提交任務(wù)
cachedThreadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " : " + o);
try {
// 間隔1s
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
});
}
}
執(zhí)行結(jié)果:
pool-1-thread-1 : first
pool-1-thread-1 : second
pool-1-thread-1 : third
因為間隔時間長跑筝,下一個任務(wù)運行時死讹,上一個任務(wù)已經(jīng)完成,所以線程可以繼續(xù)復(fù)用曲梗,如果間隔時間調(diào)短赞警,那么部分線程將會使用新線程來運行。
把每個任務(wù)等待時間從3s調(diào)低至1s:
執(zhí)行結(jié)果:
pool-1-thread-1 : first
pool-1-thread-2 : second
pool-1-thread-1 : third
- 定長線程池 Executors.newFixedThreadPool(int nThreads)
創(chuàng)建一個固定線程數(shù)量的線程池虏两,參數(shù)手動傳入
package com.test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class PoolTest {
public static void main(String[] args) {
// 創(chuàng)建可緩存線程池
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
List<String> list = new ArrayList<String>();
list.add("first");
list.add("second");
list.add("third");
list.add("fourth");
list.forEach(o -> {
try {
// 間隔1s
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 遍歷集合提交任務(wù)
fixedThreadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " : " + o);
try {
// 間隔1s
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
});
}
}
執(zhí)行結(jié)果:
pool-1-thread-1 : first
pool-1-thread-2 : second
pool-1-thread-3 : third
pool-1-thread-1 : fourth
- 定時線程池 Executors.newScheduledThreadPool(int corePoolSize)
創(chuàng)建一個定長線程池愧旦,支持定時及周期性任務(wù)執(zhí)行
package com.test;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class PoolTest {
public static void main(String[] args) {
// 創(chuàng)建定長線程池、支持定時定罢、延遲笤虫、周期性執(zhí)行任務(wù)
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " : 1秒后每隔3秒執(zhí)行一次");
}
}, 1, 3, TimeUnit.SECONDS);
}
}
執(zhí)行結(jié)果:
pool-1-thread-1 : 1秒后每隔3秒執(zhí)行一次
pool-1-thread-1 : 1秒后每隔3秒執(zhí)行一次
pool-1-thread-2 : 1秒后每隔3秒執(zhí)行一次
pool-1-thread-2 : 1秒后每隔3秒執(zhí)行一次
pool-1-thread-2 : 1秒后每隔3秒執(zhí)行一次
pool-1-thread-2 : 1秒后每隔3秒執(zhí)行一次
pool-1-thread-2 : 1秒后每隔3秒執(zhí)行一次
三、自定義線程池
常用構(gòu)造函數(shù):
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
參數(shù)說明:
1祖凫、corePoolSize 核心線程數(shù)大小琼蚯,當線程數(shù)<corePoolSize ,會創(chuàng)建線程執(zhí)行runnable
2惠况、maximumPoolSize 最大線程數(shù)遭庶, 當線程數(shù) >= corePoolSize的時候,會把runnable放入workQueue中
3稠屠、keepAliveTime 保持存活時間峦睡,當線程數(shù)大于corePoolSize的空閑線程能保持的最大時間。
4权埠、unit 時間單位
5榨了、workQueue 保存任務(wù)的阻塞隊列
6、threadFactory 創(chuàng)建線程的工廠
7攘蔽、handler 拒絕策略
任務(wù)執(zhí)行順序:
1阻逮、當線程數(shù)小于corePoolSize時,創(chuàng)建線程執(zhí)行任務(wù)秩彤。
2叔扼、當線程數(shù)大于等于corePoolSize并且workQueue沒有滿時,放入workQueue中
3漫雷、線程數(shù)大于等于corePoolSize并且當workQueue滿時瓜富,新任務(wù)新建線程運行,線程總數(shù)要小于maximumPoolSize
4降盹、當線程總數(shù)等于maximumPoolSize并且workQueue滿了的時候執(zhí)行handler的rejectedExecution与柑。也就是拒絕策略。
ThreadPoolExecutor默認有四個拒絕策略:
1、new ThreadPoolExecutor.AbortPolicy() 直接拋出異常RejectedExecutionException
2价捧、new ThreadPoolExecutor.CallerRunsPolicy() 直接調(diào)用run方法并且阻塞執(zhí)行
3丑念、new ThreadPoolExecutor.DiscardPolicy() 直接丟棄后來的任務(wù)
4、new ThreadPoolExecutor.DiscardOldestPolicy() 丟棄在隊列中隊首的任務(wù)
緩沖隊列BlockingQueue:
BlockingQueue是雙緩沖隊列结蟋。BlockingQueue內(nèi)部使用兩條隊列脯倚,允許兩個線程同時向隊列一個存儲,一個取出操作嵌屎。在保證并發(fā)安全的同時推正,提高了隊列的存取效率。
常用的幾種BlockingQueue:
ArrayBlockingQueue(int i):規(guī)定大小的BlockingQueue宝惰,其構(gòu)造必須指定大小植榕。其所含的對象是FIFO順序排序的。
LinkedBlockingQueue()或者(int i):大小不固定的BlockingQueue尼夺,若其構(gòu)造時指定大小尊残,生成的BlockingQueue有大小限制,不指定大小淤堵,其大小有Integer.MAX_VALUE來決定夜郁。其所含的對象是FIFO順序排序的。
PriorityBlockingQueue()或者(int i):類似于LinkedBlockingQueue粘勒,但是其所含對象的排序不是FIFO竞端,而是依據(jù)對象的自然順序或者構(gòu)造函數(shù)的Comparator決定。
SynchronizedQueue():特殊的BlockingQueue庙睡,對其的操作必須是放和取交替完成事富。
package com.test;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class PoolTest {
public static void main(String[] args) {
// 工作隊列
LinkedBlockingDeque<Runnable> workQueue = new LinkedBlockingDeque<Runnable>();
// 拒絕策略
RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 10, 20, TimeUnit.MILLISECONDS, workQueue, handler);
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println("自定義線程池");
}
});
}
}