本文介绍如何向线程池提交任务,并获得任务的执行结果。然后模拟 线程池中的线程在执行任务的过程中抛出异常时,该如何处理。
一,执行具体任务的线程类
要想 获得 线程的执行结果,需实现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