new Thread(new Runnable() {
public void run() {
.............
.............
.............
}
}).start();
如果我将在main中执行此操作,它将创建一个新线程并将向其提交任务以进行异步计算.
如果您看到FutureTask documentation,它还会说:
A cancellable asynchronous computation. This class provides a base
implementation of Future, with methods to start and cancel a
computation, query to see if the computation is complete, and retrieve
the result of the computation.
那么FutureTask是一个异步计算如何在内部创建线程并提交我们在实例化FutureTask时提供的任务,如:
FutureTask f = new FutureTask(new MyCallable());
否则它不能是异步计算,请提供FutureTask source code中的代码片段,它将任务提交给线程,以使其进行异步计算.谢谢.
我得到了答案.它基本上是尝试在与调用者相同的线程中运行任务.在给定的代码中非常明显:
当你调用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
}
}