您的位置:首页 > 其它

使用callable获取子线程的返回值

2017-08-27 17:58 344 查看
 我们都知道实现多线程可以继承Thread类或者是实现Runnable接口,但是有的时候我们需要子线程返回处理结果,而run方法又是void的,下意识里我们就想到在run方法里使用全局变量,但是总感觉这种处理方式怪怪的,其实java本身提供了这个有返回值的子线程,那就是Callable接口。

class lianxi implements Callable<Integer>{
private int n;
private List<Integer> list;
public lianxi(int n){
this.n = n;
this.list = constract();
System.out.println(list);
}

public List<Integer> constract(){
List<Integer> list = new ArrayList<>(n);
list.add(0);
list.add(1);
if(n >= 3)
for (int i = 3; i < n; i++)
list.add(list.get(i-2)+list.get(i-3));
return list;

}
@Override
public Integer call() throws Exception {
Integer sum = 0;
for(Integer s : list)
sum = sum+s;
return sum;
}

在实现的时候,我们需要保持callable的类型参数与我们期望返回的类型一致,然后重写call方法。类里面的其他方法是实现了一个伪斐波那契数列,还有一点bug,博主懒得解决了,算法大神请轻喷。

ExecutorService exe = Executors.newCachedThreadPool();
ArrayList<Future<Integer>> results = new ArrayList<>();
for(int i = 1;i < 20; i++)
results.add(exe.submit(new lianxi(i)));//submit方法会返回一个future对象
for(Future<Integer> fs : results)
try {
System.out.println(fs.get());
} catch (InterruptedException e) {
System.out.println(e);
return;
} catch (ExecutionException e) {
System.out.println(e);
} finally {
exe.shutdown();
}

这一块是调用时的代码。

结果如下:[0, 1]

[0, 1]

[0, 1, 1]

[0, 1, 1, 2]

[0, 1, 1, 2, 3]

.......

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]

1

1

2

.......

1596

2583 .........

ok,成功实现
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: