concurrent包中Executor接口的主要類的關系圖如下:
Executor接口非常單一,就是執行一個Runnable的命令。
public interface Executor { void execute(Runnable command);}
ExecutorService接口擴展了Executor接口,增加狀態控制,執行多個任務返回Future。
關于狀態控制的方法:
// 發出關閉信號,不會等到現有任務執行完成再返回,但是現有任務還是會繼續執行,// 可以調用awaitTermination等待所有任務執行。不再接受新的任務。void shutdown();// 立刻關閉,嘗試取消正在執行的任務(不保證會取消成功),返回未被執行的任務List<Runnable> shutdownNow();// 是否發出關閉信號boolean isShutdown();// 是否所有任務都執行完畢在shutdown之后,也就是如果不調用shutdownNow或者// shutdown是不可能返回trueboolean isTerminated();// 進行等待直到所有任務完成或者超時boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;
提交單個任務,立刻返回一個Future存儲任務執行的實時狀態
<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;
通過上面的代碼可以看出ExecutorService可以執行兩種類型的任務:Runnable和Callable,而Callable用的更加多。兩者區別很簡單,前者不會返回執行結果而后者會返回一個執行結果:
public interface Callable<V> { V call() throws Exception;}
接著說說Future,也就是執行任務的返回類型。Future可以看成是一張發票。比如你送件衣服到洗衣店清洗,他們會開張發票給你,你拿著發票可以去拿回你洗好的衣服或者去洗衣店問衣服是否洗好了等等。
public interface Future<V> { //取消任務,參數mayInterruptIfRunning為true時,如果要取消的任務正在執行, //會把執行這個任務的線程設為中斷,為false時,正在執行的任務會被允許執行完成 boolean cancel(boolean mayInterruptIfRunning); boolean isCancelled(); boolean isDone(); //獲取執行結果,如果任務執行中,會等到任務完成再返回 V get() throws InterruptedException, ExecutionException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;}
最后看看ScheduledExecutorService接口,該接口是ExecutorService的子接口,增加了定時執行任務的功能:
public interface ScheduledExecutorService extends ExecutorService { public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit); public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit); // 等待一定時間然后開始執行一個任務,每隔period參數設置的時間 // 重復一次,(多線程執行) public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit); // 等待一定時間然后開始執行一個任務,完成后,等待delay參數設置的時間 // 然后在執行一次任務。(單線程執行) public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit);}
這篇文章主要就講到了concurrent包關于線程池的相關接口,接下來會講AbstractExecutorService,ThreadPoolExecutor和ScheduledThreadPoolExecutor。
新聞熱點
疑難解答