多线程篇七:通过Callable和Future获取线程池中单个务完成后的结果

本文介绍如何使用Callable接口配合Future获取线程执行结果,包括创建线程池、提交Callable任务并获取结果,以及利用CompletionService处理多个任务。

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

使用场景:如果需要拿到线程的结果,或者在线程完成后做其他操作,可以使用Callable 和 Futrue

1.定义一个线程池,向线程池中提交单个callable任务

ExecutorService threadPools=Executors.newSingleThreadExecutor();
        Future<String> future=threadPools.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(2000);//模拟任务处理2S
                return "hello";
            }
            
        });
        System.out.println("等待结果。。。。。");
        try {
            System.out.println("获取到结果:"+future.get());//2S之后任务完成后获取到结果
        } catch (Exception e) {
            e.printStackTrace();
        }

2.CompletionService 用于提交一组callable任务,并获取每一个任务的结果

ExecutorService threadPools2=Executors.newFixedThreadPool(10);
        CompletionService<Integer> completetionService=new ExecutorCompletionService<Integer>(threadPools2);
        //提交10个任务
        for(int i=1;i<=10;i++){
            final int seq=i;
            completetionService.submit(new Callable<Integer>(){
                @Override
                public Integer call() throws Exception {
                    Thread.sleep(new Random().nextInt(5000));
                    return seq;
                }
                
            });
        }
        
        for(int i=1;i<=10;i++){
              Future<Integer> futures;
            try {
                futures = completetionService.take();
                System.out.println("拿到任务结果:"+futures.get());//在任务完成后拿到结果,哪个任务先完成,则先拿到结果
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

 

转载于:https://www.cnblogs.com/brant/p/6028544.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值