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

 我们都知道实现多线程可以继承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,成功实现

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值