java使用 Future 获得线程返回的结果

//执行多任务类
    public Map<String,Object> tasks(List<PddAccount> pddAccounts,int length) throws InterruptedException {
        Map<String,Object> map=new HashMap<>();
        List<PddAccount> rlist=new ArrayList<>();
        ExecutorService pool = Executors.newFixedThreadPool(30);

        for (int i = 0; i < pddAccounts.size(); i++) {
            PddAccount account = pddAccounts.get(i);
            try{
                Callable<Object> callable = new Callable<Object>() {
                    @Override
                    public Object call() throws Exception {
                        boolean validAccountAndLength = getValidAccountAndLength(account);
                        return validAccountAndLength;
                    }
                };

                Future<Object> future = pool.submit(callable);
                boolean o = (boolean)future.get();
                if(o){
                    rlist.add(account);
                }
                if(rlist.size() >= length){
                    pool.shutdown();//快速关闭线城池

                    map.put("list",rlist);
                    return map;
                }
            }catch (Exception e){
                System.out.println("出现异常");
            }
        }
        map.put("list",rlist);
        return map;
    }

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用CountDownLatch配合Future和Callable实现返回线程的结果。以下是示例代码: ```java import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ThreadDemo { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executorService = Executors.newCachedThreadPool(); CountDownLatch latch = new CountDownLatch(1); Future<Integer> future = executorService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { int result = 0; // 执行一些耗时的操作 for (int i = 0; i < 1000000; i++) { result += i; } return result; } }); new Thread(() -> { try { latch.await(); System.out.println("子线程返回结果:" + future.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } }).start(); // 唤醒等待的子线程 latch.countDown(); executorService.shutdown(); } } ``` 在上面的代码中,我们创建了一个CountDownLatch对象,然后在主线程中启动了一个子线程,子线程执行了一些耗时的操作,返回了结果。在主线程中,我们使用Future对象获取了子线程返回结果,并且在启动了一个新的线程来处理这个返回结果。在新线程中,我们使用CountDownLatch的await()方法等待主线程调用countDown()方法唤醒它,然后再通过Future的get()方法获取子线程返回结果。最后,我们调用ExecutorService的shutdown()方法关闭线程池。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值