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

本文介绍如何使用Callable接口实现具有返回值的多线程应用,并通过实例演示了如何构造并获取多线程的返回结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

### Java 线程池获取 Future 返回值 为了在线程池获取线程的返回值,通常会使用 `Callable` 接口替代传统的 `Runnable` 接口。这是因为 `Runnable` 不支持返回结果而 `Callable` 支持。当任务被提交至线程池之后,它将返回一个实现了 `Future` 接口的对象。此对象可用于查询任务的状态以及检索执行的结果。 下面是一个简单的例子展示如何利用 Callable 和 Future 来获得来自线程的任务完成后的返回值[^1]: ```java import java.util.concurrent.*; public class ThreadPoolExample { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newSingleThreadExecutor(); // 创建一个可调用任务实例 Callable<Integer> task = () -> { System.out.println("正在执行任务..."); Thread.sleep(2000); // 模拟耗时操作 return 123; // 假设这是计算得到的结果 }; // 提交任务并接收未来对象 Future<Integer> future = executor.submit(task); // 执行其他工作... System.out.println("主线程继续运行..."); // 当准备好时尝试获取结果 try { Integer result = future.get(); // 这里可能会阻塞直到任务结束 System.out.println("任务已完成,结果为:" + result); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } // 关闭线程池 executor.shutdown(); } } ``` 此外,如果存在多个需要监控其进度的任务,则可以考虑采用 `CompletionService` 结合 `ExecutorCompletionService` 的方式来简化管理流程。这种方式允许更灵活地处理并发任务及其对应的返回值
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值