Java多线程的异步计算,java – FutureTask如何进行异步计算

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值