package com.tianci.demo.mybatis.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 練習(xí)線程池
*/
public class ThreadPoolTest {
/**
* 為什么不用new thread,而要用ExecutorSerivice
* new thread壞處
* 1. new Thread 性能差
* 2. 缺乏統(tǒng)一管理曹锨,相互之間競(jìng)爭(zhēng)门粪,可能占用過(guò)多系統(tǒng)資源導(dǎo)致死機(jī)
* 3. 功能少段直,不能定時(shí)執(zhí)行,定期執(zhí)行
* ExecutorService好處
* 1. 減少對(duì)象創(chuàng)建消亡開銷
* 2. 有效控制最大并發(fā)線程數(shù)嘉涌,提高系統(tǒng)資源利用率穷劈,避免過(guò)多資源競(jìng)爭(zhēng),避免堵塞
* 3. 提供很多功能冤荆,定時(shí)執(zhí)行朴则,定期執(zhí)行
*/
/**
* corePoolSize:核心線程數(shù),創(chuàng)建之后不會(huì)釋放钓简。
* maximumPoolSize:最大線程數(shù)乌妒。
* keepAliveTime:線程空閑時(shí)所允許保存的最大時(shí)間,超過(guò)時(shí)間外邓,非核心線程將被釋放撤蚊。
* unit:時(shí)間單位。
* workQueue:任務(wù)隊(duì)列损话,存儲(chǔ)暫時(shí)無(wú)法執(zhí)行的任務(wù)侦啸。
*/
public static void main(String[] args) {
/* return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>()); */
/*可緩存線程池:大量耗時(shí)任務(wù)不適合,適合生命周期短的任務(wù)丧枪。*/
ExecutorService cachePool = Executors.newCachedThreadPool();
/*return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));*/
/*單線程池:保證任務(wù)按順序執(zhí)行*/
ExecutorService singlePool = Executors.newSingleThreadExecutor();
/*return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());*/
/*固定線程數(shù)線程池*/
ExecutorService fixedPool = Executors.newFixedThreadPool(3);
/*super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());*/
/*固定線程數(shù)光涂,支持定時(shí)和周期性任務(wù)*/
ExecutorService schedulePool = Executors.newScheduledThreadPool(5);
}
}
execute,submit,shundown,awaitTermination方法
先說(shuō)execute和submit
上源碼
public interface Executor {
void execute(Runnable command);
}
public interface ExecutorService extends Executor {
Future<?> submit(Runnable task);
<T> Future<T> submit(Runnable task, T result);
<T> Future<T> submit(Callable<T> task);
}
- 入?yún)⒉灰粯?/li>
- 一個(gè)有返回值,一個(gè)沒(méi)有
- submit可以進(jìn)行exception處理
execute的入?yún)⑹荝unnable類拧烦,submit的入?yún)⑹荝unnable和Callable忘闻。
上callable源碼
@FunctionalInterface
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
submit有返回值,可以根據(jù)返回值判斷邏輯恋博,繼續(xù)下面的操作齐佳。
看callable的源碼也知道實(shí)現(xiàn)call方法后,可以拋出異常交播,進(jìn)行exception處理重虑。
再說(shuō)shundown和awaitTermination
shundown:平滑的關(guān)閉線程池,停止接受新任務(wù)秦士,等待已提交的任務(wù)執(zhí)行完畢后關(guān)閉線程池。
awaitTermination:當(dāng)?shù)却^(guò)設(shè)定時(shí)間時(shí)永高,檢測(cè)線程池是否關(guān)閉隧土,關(guān)閉返回true,否則返回false命爬。