【多线程实践】返回各个线程的结果Future的使用

24 篇文章 0 订阅

例子:

try {

        List<Map<String, Object>> resList = new ArrayList<Map<String, Object>>();
        // 创建线程池:当前可用数就可以了;多了也没用,cpu执行不过来还是会在等待;
        ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        // 各个线程的结果
        List<Future<Boolean>> threadList = new ArrayList<Future<Boolean>>();
        List<String> ids = new ArrayList<String>();
        for (final String id : ids) {
            // 为了提高效率,这里使用多线程对数据库操作
            Future<Boolean> task = executor.submit(new Callable<Boolean>() {
                public Boolean call() throws Exception {
                    boolean res = false;
                    try {
                        res = sendMsgById(id);
                    } catch (Exception e) {
                        logger.info("发送消息:线程出现异常");
                    }
                    return res;// 返回的是线程结果,不是方法结果
                }
            });
            threadList.add(task);// 将线程放进list
        }
        // 获取所有线程的结果
        for (Future<Boolean> future : threadList) {
            // 线程返回的结果,此处可以把线程阻塞;
            Boolean threadRes = future.get();
            // 线程完成,继续下面判断;
            if (!threadRes) {// 失败的线程
                Map<String, Object> resultMap = new HashMap<String, Object>();
                resultMap.put("result", "error");
                resultMap.put("message", "查询出现失败的线程,请联系IT处理");
            }
        }
        // 获取所有线程的结果结束:因为future.get()会阻塞主线程;所以只有所有子线程结束后才会继续往下走

        // 走到这里就已经得到所有的线程结束//

}catch(Exception e){

}finally{

executor.shutdown();

}

 

  • 0
    点赞
  • 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、付费专栏及课程。

余额充值