Runnable、Callable、Future和FutureTask

Runnable、Callable、Future和FutureTask

線程池:
繼承關(guān)系:ThreadPoolExecutor->ExecutorService->Executor
Executors:ThreadPoolExecutor的工廠類,生成不同的線程池

主要關(guān)系:在線程池中:

<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
Callable:

位于java.util.concurrent包下,類似于Runnable:

public interface Callable<V> {
    V call() throws Exception;
}
Future類:

位于java.util.concurrent包下
Future就是對于具體的Runnable或者Callable任務(wù)的執(zhí)行結(jié)果進行取消、查詢是否完成、獲取結(jié)果。
必要時可以通過get方法獲取執(zhí)行結(jié)果,該方法會阻塞直到任務(wù)返回結(jié)果。

public interface Future<V> {
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
FutureTask:

FutureTask是Future的實現(xiàn)類,用來實現(xiàn)真正的Future工作,用來對Callable或者Runbale的任務(wù)實現(xiàn)監(jiān)控:
構(gòu)造方法:
注意第二個,因為Runnable無返回值,所以要手動提前寫一個結(jié)果,當(dāng)Runnable執(zhí)行完畢返回這個值,當(dāng)然不關(guān)心返回值的話傳null

public FutureTask(Callable<V> callable) {
}
public FutureTask(Runnable runnable, V result) {
}

線程池繼承關(guān)系:
繼承關(guān)系:ThreadPoolExecutor->ExecutorService->Executor
Executors:ThreadPoolExecutor的工廠類,生成不同的線程池

public interface Executor {
    void execute(Runnable command);
}

public interface ExecutorService extends Executor {

    void shutdown();
    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;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容