public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
複製代碼
特色
核心線程數爲0
最大線程數爲Integer.MAX_VALUE
阻塞隊列是SynchronousQueue
非核心線程空閒存活時間爲60秒
工做機制
提交任務
由於沒有核心線程,因此任務直接加到SynchronousQueue隊列
判斷是否有空閒線程,若是有,就去取出任務執行
若是沒有空閒線程,就新建一個線程執行
執行完任務的線程,還能夠存活60秒,若是在這期間,接到任務,能夠繼續活下去;不然,被銷燬
使用場景
併發執行大量短時間的小任務
newSingleThreadExecutor(單線程的線程池)
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
複製代碼
特色
核心線程數爲1
最大線程數也爲1
keepAliveTime爲0
阻塞隊列是LinkedBlockingQueue
工做機制
提交任務
線程池是否有一條線程在,若是沒有,新建線程執行任務
若是有,任務加到阻塞隊列
當前的惟一線程,從隊列取任務,執行完一個,再繼續取,一我的(一條線程)夜以繼日地幹活
使用場景
newScheduledThreadPool(定時及週期執行的線程池)
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue(), threadFactory);
}
複製代碼
特色
最大線程數爲Integer.MAX_VALUE
阻塞隊列是DelayedWorkQueue
keepAliveTime爲0
scheduleAtFixedRate() :按某種速率週期執行
scheduleWithFixedDelay():在某個延遲後執行
工做機制
添加一個任務
線程池中的線程從 DelayQueue 中取任務
線程從 DelayQueue 中獲取 time 大於等於當前時間的task
執行完後修改這個 task 的 time 爲下次被執行的時間
這個 task 放回DelayQueue隊列中
使用場景
週期性執行任務的場景,須要限制線程數量的場景
自定義ThreadPool
copy一份AbortPolicy改個名字,加些本身想加的內容(例如加個輸出)。
public static class MyPolicy implements RejectedExecutionHandler {
public MyPolicy() { }
public void rejectedExecution(Runnable r, java.util.concurrent.ThreadPoolExecutor e) {
// 新增
System.out.println("拒絕");
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}
複製代碼
copy一份DefaultThreadFactory改個名字,加些本身想加的內容(例如加個輸出)。
static class MyThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
MyThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
// 新增
System.out.println(t.getName() + " has been created");
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
複製代碼
測試
public static void main(String agrs[]) throws Exception{
int corePoolSize = 2;
int maximumPoolSize = 4;
long keepAliveTime = 10;
TimeUnit unit = TimeUnit.SECONDS;
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(2);
ThreadFactory threadFactory = new MyThreadFactory();
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit,
workQueue, threadFactory,new MyPolicy());
executor.prestartAllCoreThreads(); // 預啓動全部核心線程
for (int i = 1; i <= 10; i++) {
executor.execute(()-> System.out.println(Thread.currentThread().getId()));
}
System.in.read(); //阻塞主線程
}
複製代碼