0

我想了解FutureTaskCollections的工作情況。根據我的理解,我可以使用ExecutorService創建一個線程池。稍後,您可以將RunnableCallable換成FutureTask並執行它。之後,您可以使用Future對象來檢查獲取結果或檢查任務是否正在運行。但是這在內部是如何做到的?集合中的FutureTask如何在內部工作?

我想了解的是當你傳遞Callable接口時發生在場景後面的事情。我有幾個問題是

  1. 是否FutureTask本身運行一個線程內部不斷地檢查可調用命令已經執行完畢?如果不是,那麼它是如何知道命令何時完成執行的?

  2. get()方法是如何工作的?它如何獲得從Callable接口返回的值?

看看我無法弄清楚的文檔。是否有任何代碼示例可以幫助我們理解幕後故事。

回答

0

瀏覽grepcode網站,你會得到答案。

ExecutorService接口,由AbstractExecutorService實現,具有下面的submit()方法的實現。

public <T> Future<T> submit(Callable<T> task) { 
    if (task == null) throw new NullPointerException(); 
    RunnableFuture<T> ftask = newTaskFor(task); 
    execute(ftask); 
    return ftask; 
} 

protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) { 
    return new FutureTask<T>(callable); 
} 

grepcode爲Executor提供

grepcode爲FutureTask

public FutureTask(Callable<V> callable) { 
    if (callable == null) 
     throw new NullPointerException(); 
    sync = new Sync(callable); 
} 


private final class Sync extends AbstractQueuedSynchronizer { 
    Sync(Callable<V> callable) { 
     this.callable = callable; 
    } 
} 

public V get() throws InterruptedException, ExecutionException { 
    return sync.innerGet(); 
} 

V innerGet() throws InterruptedException, ExecutionException { 
     acquireSharedInterruptibly(0); 
     if (getState() == CANCELLED) 
      throw new CancellationException(); 
     if (exception != null) 
      throw new ExecutionException(exception); 
     return result; 
    } 
execute方法的不同實施