栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

用Future与CountDownLatch实现多线程执行多个异步任务,任务全部完成后返回结果

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用Future与CountDownLatch实现多线程执行多个异步任务,任务全部完成后返回结果

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;


public class TestFuture {
    public static void main(String[] args) {
        TestFuture testFuture = new TestFuture();
        // 初始为三个任务数
        int taskCount = 3;
        List> futures = new ArrayList<>(taskCount);
        // CountDownLatch作为递减计数器,一个线程完成了一个任务,计数器减一,减为0时表示任务全部完成
        CountDownLatch downLatch = new CountDownLatch(taskCount);

        ExecutorService executorService = new ThreadPoolExecutor
                (taskCount, 5, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));

        for (int i = 0; i < taskCount; i++) {
            // 开启三个异步任务
            Future future = executorService.submit(testFuture.executeTask(i, downLatch));
            futures.add(future);
        }

        System.out.println("do other things");

        try {
            // 在downLatch不为0时,主线程会在此阻塞
            downLatch.await();
            executorService.shutdown();
            // 通过future获取结果
            List result = testFuture.getFutureResult(futures);
            for (String s : result) {
                System.out.println(s);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public Callable executeTask(int i, CountDownLatch downLatch) {
        return () -> {
            Thread.sleep(i * 1000L);
            downLatch.countDown();
            return "Result " + Thread.currentThread().getName();
        };
    }

    public List getFutureResult(List> futures) {
        List result = new ArrayList<>(3);
        for (Future future : futures) {
            if (future.isDone() && !future.isCancelled()) {
                try {
                    result.add(future.get());
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/315599.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号