Futures JAVA,Java并发Futures和Callables类

java.util.concurrent.Callable对象可以返回由线程完成的计算结果,而runnable接口只能运行线程。 Callable对象返回Future对象,该对象提供监视线程执行的任务进度的方法。 Future对象可用于检查Callable的状态,然后线程完成后从Callable中检索结果。 它还提供超时功能。

语法

//submit the callable using ThreadExecutor

//and get the result as a Future object

Future result10 = executor.submit(new FactorialService(10));

//get the result using get method of the Future object

//get method waits till the thread execution and then return the result of the execution.

Long factorial10 = result10.get();

实例

以下TestThread程序显示了基于线程的环境中Futures和Callables的使用。

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

public class TestThread {

public static void main(final String[] arguments) throws InterruptedException, ExecutionException {

ExecutorService executor = Executors.newSingleThreadExecutor();

System.out.println("Factorial Service called for 10!");

Future result10 = executor.submit(new FactorialService(10));

System.out.println("Factorial Service called for 20!");

Future result20 = executor.submit(new FactorialService(20));

Long factorial10 = result10.get();

System.out.println("10! = " + factorial10);

Long factorial20 = result20.get();

System.out.println("20! = " + factorial20);

executor.shutdown();

}

static class FactorialService implements Callable{

private int number;

public FactorialService(int number) {

this.number = number;

}

@Override

public Long call() throws Exception {

return factorial();

}

private Long factorial() throws InterruptedException{

long result = 1;

while (number != 0) {

result = number * result;

number--;

Thread.sleep(100);

}

return result;

}

}

}

这将产生以下结果。

Factorial Service called for 10!

Factorial Service called for 20!

10! = 3628800

20! = 2432902008176640000

¥ 我要打赏

纠错/补充

收藏

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值