- 如果當(dāng)前線程數(shù)不超過coreSize蚜点,則新建一個(gè)線程,執(zhí)行新的任務(wù)
- 如果當(dāng)前coreSize已經(jīng)滿了群井,且沒有空閑的線程赴恨,則會(huì)把這個(gè)任務(wù)丟到阻塞隊(duì)列當(dāng)中
- 如果阻塞隊(duì)列也滿了(比如ArrayBlockingQueue,或者LinkedBQ等有界隊(duì)列時(shí))箕憾,則會(huì)啟動(dòng)新的臨時(shí)線程
- 如果所有的線程都滿了牡借,且超過maxSize的時(shí)候,就會(huì)把任務(wù)交給飽和策略處理
下面的Demo中袭异,前面2個(gè)任務(wù)會(huì)丟到coreThread執(zhí)行钠龙,接下來6個(gè)任務(wù)會(huì)存在阻塞隊(duì)列當(dāng)中,后面來的2個(gè)新任務(wù)御铃,會(huì)創(chuàng)建maxThread來執(zhí)行碴里。
- 如果遍歷的次數(shù)超過10,那么就會(huì)調(diào)用飽和策略
- 如果LinkedBlockingQueue沒有設(shè)置長(zhǎng)度上真,那么永遠(yuǎn)也不會(huì)創(chuàng)建超過coreSize的線程
public static void main(String args[]) throws Exception{
int corePoolSize = 2;
int maximumPoolSize = 4;
long keepAliveTime = 10;
TimeUnit unit = TimeUnit.SECONDS;
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(6);
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit,workQueue);
for(int i=0;i<10;i++){
Thread th=new Thread(new Runnable(){
@Override
public void run() {
System.out.println("i am in"+Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("i am out"+Thread.currentThread().getName());
}});
executor.execute(th);
}
System.in.read();
}