JAVA 线程池之Callable返回结果

本文介绍如何向线程池提交任务,并获得任务的执行结果。然后模拟 线程池中的线程在执行任务的过程中抛出异常时,该如何处理。

一,执行具体任务的线程类

要想 获得 线程的执行结果,需实现Callable接口。FactorialCalculator 计算 number的阶乘,具体实现如下:

 1 import java.util.concurrent.Callable;
 2 import java.util.concurrent.TimeUnit;
 3 
 4 /**
 5  * Created by Administrator on 2017/9/26.
 6  */
 7 public class FactorialCalculator implements Callable<Integer> {
 8 
 9     private Integer number;
10 
11     public FactorialCalculator(Integer number) {
12         this.number = number;
13     }
14     public Integer call() throws Exception {
15         int result = 1;
16 
17         if (number == 0 || number == 1) {
18             result = 1;
19         }else {
20             for (int i = 2; i < number; i++) {
21                 result *= i;
22                 TimeUnit.MICROSECONDS.sleep(200);
23                 if (i == 5) {
24                     throw new IllegalArgumentException("excepion happend");//计算5以上的阶乘都会抛出异常. 根据需要注释该if语句
25                 }
26             }
27         }
28         System.out.printf("%s: %d\n", Thread.currentThread().getName(), result);
29         return result;
30     }
31 }

上面23行--25行的if语句表明:如果number大于5,那么 if(i==5)成立,会抛出异常。即模拟 执行5 以上的阶乘时,会抛出异常。

二,提交任务的Main类

下面来看看,怎样向线程池提交任务,并获取任务的返回结果。我们一共向线程池中提交了10个任务,因此创建了一个ArrayList保存每个任务的执行结果。

第一行,首先创建一个线程池。第二行,创建List保存10个线程的执行结果 所要存入的地方,每个任务是计算阶乘,因此线程的返回结果是 Integer。而这个结果只要计算出来了,是放在Future<Integer&g

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值