[英]How FutureTask is asynchronous computation
new Thread(new Runnable() {
public void run() {
.............
.............
.............
}
}).start();
如果我將在main中執行此操作,它將創建一個新線程並將向其提交任務以進行異步計算。
如果您看到FutureTask 文檔,它還會說:
可取消的異步計算。 此類提供Future的基本實現,包括啟動和取消計算的方法,查詢計算是否完成的查詢,以及檢索計算結果。
那么FutureTask
是一個asynchronous computation
如何在內部創建線程並提交我們在實例化FutureTask
時提供的任務,如:
FutureTask f = new FutureTask(new MyCallable());
否則它不能是異步計算,請提供FutureTask
源代碼中的代碼片段,它將任務提交給線程,以使其進行異步計算。 謝謝。
我得到了答案。 它基本上是嘗試在與調用者相同的線程中運行任務。 在給定的代碼中非常明顯:
當你調用futureTask.run()
它只調用sync.innerRun();
和sync
是內部類Sync
的實例。 因為它只是在同一個線程中的可調用對象上調用call()
。
void innerRun() {
if (!compareAndSetState(READY, RUNNING))
return;
runner = Thread.currentThread(); //here it is getting the current thread
if (getState() == RUNNING) {
V result;
try {
result = callable.call();//here calling call which executes in the caller thread.
} catch (Throwable ex) {
setException(ex);
return;
}
set(result);
} else {
releaseShared(0); // cancel
}
}
那么FutureTask是一個異步計算如何在內部創建線程並提交我們在實例化FutureTask時提供的任務,如:
FutureTask
不是為用戶直接使用而設計的。 它旨在通過ExecutorService
接口和實現它的類來使用。 這些類使用FutureTask
並分叉線程等。您可能需要閱讀有關如何使用ExecutorService
並發類的更多信息。
ThreadPoolExecutor
類是實際管理ThreadPoolExecutor
的主要類。 通常,您調用Executors.newCachedThreadPool()
或Executors.newFixedThreadPool(10)
來獲取它的實例。
// create a thread pool with 10 workers
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// define your jobs somehow
for (MyCallable job : jobsToDo) {
// under the covers this creates a FutureTask instance
Future future = threadPool.submit(job);
// save the future if necessary in a collection or something
}
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();
// now we can go back and call `future.get()` to get the results from our jobs
從學術角度來看,TPE擴展了AbstractExecutorService
,你可以看到FutureTask
類用於管理線程池中的任務:
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);
}
TPE中的代碼非常復雜,並且顯示執行異步調用的“代碼段”並不容易。 TPE會查看是否需要向池中添加更多線程。 將其提交給任務隊列,該隊列可以拒絕它或接受它,然后線程將任務隊列化並在后台運行它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.