一,Executor,ExecutorService,Executors
- 1,Executors
java.util.concurrent提供了一種靈活的線程池實現作為Executor框架的一部分.在java類庫中,任務執(zhí)行的主要抽象不是Thread,而是Executor.
** Executor提供一種將任務提交與每個任務將如何運行的機制(包括線程使用的細節(jié)裆针、調度等)分離開來的方法**功偿。通常使用 Executor 而不是顯式地創(chuàng)建線程筝尾。
public interface Executor {
void execute(Runnable command);
}
- 2,ExecutorService
為了解決執(zhí)行服務的生命周期,ExecutorService接口擴展了Executor接口,添加了一些用于生命周期管理的方法
public interface ExecutorService extends Executor {
//平緩的關閉過程:不接受新的任務,同時等待已經提交的任務完成(包括哪些還沒有開始執(zhí)行的任務
void shutdown();
//執(zhí)行粗暴的關閉過程:他將嘗試取消所有運行中的任務,并且不再啟動隊列中尚未開始執(zhí)行的任務
List<Runnable> shutdownNow();
boolean isShutdown();
boolean isTerminated();
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException;
<T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException;
<T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
- 3,Executors
Executor框架的一個工具類
二,線程池
newFixedThreadPool
newFixedThreadPool創(chuàng)建一個固定長度的線程池,每當提交一個任務時就創(chuàng)建一個線程,直到達到線程池的最大數量,這時線程池的規(guī)模將不再變化.如果某個線程由于發(fā)生了未預期的Excepiton而結束,那么線程池會補充一個新的線程newCachedThreadPool
newCachedThreadPool將創(chuàng)建一個可緩存的線程池,如果線程池的當前規(guī)模超過了處理請求時,那么將回收空閑的線程,而當需求增加時,則可以添加新的線程,線程池的規(guī)模不存在任何限制newSingleThreadExecutor
newSingleThreadExecutor是一個單線程的Executor,他創(chuàng)建單個工作者線程來執(zhí)行任務,如果這個線程異常結束,會創(chuàng)建另一個線程來替代. newSingleThreadExecutor確保按照任務在隊列中的順序來串行執(zhí)行newScheduledThreadPool
newScheduledThreadPool創(chuàng)建了一個固定長度的線程池,而且以延遲或定時的方式來執(zhí)行任務.
參考:
<<java編發(fā)編程實戰(zhàn)>>