首页 > 其他分享 >CountDownLatch使用示例demo

CountDownLatch使用示例demo

时间:2022-11-18 22:58:07浏览次数:39  
标签:示例 int demo List private list CountDownLatch import stu

CountDownLatch使用示例demo

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 模拟处理考试分值计算场景(包括答题卡扫描等)
 *
 * @author lyn
 * @date 2022/2/22 16:20
 */
@Slf4j
public class TestThreadPool {
    // TODO: 2022-11-18 注意 非必要不使用多线程
    // TODO: 2022-11-18 多线程并不一定比单线程快
    private static volatile AtomicInteger index = new AtomicInteger(0);
    private static ExecutorService executorService = Executors.newFixedThreadPool(5);

    public static void main(String[] args) {
        //准备基础数据
        final int totalSize = 10045;
        Random r = new Random();
        List<StuScore> list = new ArrayList<>();
        for (int i = 1; i <= totalSize; i++) {
            list.add(new StuScore(i, r.nextInt(55) + 40, r.nextInt(55) + 40, r.nextInt(55) + 40, 0));
        }
        long start = System.currentTimeMillis();

        //单线程计算 用时17450s
        //List<StuScore> result =singleJob(list);
        //多线程计算成绩 用时8573s
        List<StuScore> result = partJob(list);

        //取总分前五名展示
        List<StuScore> collect = result.stream().sorted(Comparator.comparing(StuScore::getTotalScore).reversed()).limit(5).collect(Collectors.toList());
        for (StuScore stuScore : collect) {
            log.info("学生{}", stuScore);
        }
        long cost = System.currentTimeMillis() - start;

        log.info("用时{}s", cost);
    }

    @SneakyThrows
    private static List<StuScore> partJob(List<StuScore> list) {
        //子集合的大小
        final int sonSize = 5000;
        //分割的份数
        int parts = (list.size() + sonSize - 1) / sonSize;
        //存放异步处理后结果数据
        List<StuScore> resultList = Collections.synchronizedList(new ArrayList<>());

        CountDownLatch countDownLatch = new CountDownLatch(parts);
        //分割集合
        List<List<StuScore>> partsList = IntStream.range(0, parts).boxed().parallel().map(i -> {
            int fromIndex = i * sonSize;
            long toIndex = sonSize;
            if (i + 1 == list.size()) {
                toIndex = list.size() - fromIndex;
            }
            return list.stream().skip(fromIndex).limit(toIndex).collect(Collectors.toList());
        }).collect(Collectors.toList());

        for (int i = 0; i < partsList.size(); i++) {
            List<StuScore> sonScoreList = partsList.get(i);
            //处理数据
            executorService.execute(new PartDisPose(i, sonScoreList, resultList, countDownLatch));
        }

        // 等待所有线程执行完毕
        countDownLatch.await();
        executorService.shutdown();
        return resultList;

    }

    /**
     * 分片处理内部类
     */
    private static class PartDisPose implements Runnable {

        private int count;
        private List<StuScore> sonList;
        private List<StuScore> resultList;
        private CountDownLatch countDownLatch;

        private PartDisPose(int count, List<StuScore> sonList, List<StuScore> resultList, CountDownLatch countDownLatch) {

            this.count = count;
            this.sonList = sonList;
            this.resultList = resultList;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            for (StuScore stu : sonList) {
                stu.setTotalScore(stu.getChinese() + stu.getEnglish() + stu.getMath());
                //模拟扫描答题卡等消耗的时间
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                index.incrementAndGet();
            }
            resultList.addAll(sonList);
            log.info("count: {},sonListSize: {}", count, sonList.size());
            countDownLatch.countDown();
        }
    }

    private static List<StuScore> singleJob(List<StuScore> list) {
        return list
                .stream()
                .peek(stu -> {
                    stu.setTotalScore(stu.getChinese() + stu.getEnglish() + stu.getMath());
                    //模拟扫描答题卡等消耗的时间
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                })
                .collect(Collectors.toList());
    }
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class StuScore {
   private int id;
   private int math;
   private int english;
   private int chinese;
   private int totalScore;
}

标签:示例,int,demo,List,private,list,CountDownLatch,import,stu
From: https://www.cnblogs.com/lyn8100/p/16905169.html

相关文章

  • Spring Cloud Circuit Breaker 使用示例
    SpringCloudCircuitBreaker使用示例作者:Grey原文地址:博客园:SpringCloudCircuitBreaker使用示例CSDN:SpringCloudCircuitBreaker使用示例说明SpringClo......
  • 配置OSPF虚连接示例
    介绍通过配置虚连接使非骨干区域与骨干区域连通的过程。组网需求在下图中,Area2没有与骨干区域Area0直接相连。Area1被用作传输区域(TransitArea)来连接Area2和Area0。Rout......
  • Tomcat部署、优化、多示例部署、负载均衡(群集,要安装nginx)
    目录:1、Tomcat核心组件2、Tomcat功能组件结构3、Tomcat请求过程4、Tomcat工作模式5、Tomcat部署方式6、Tomcat顶层架构7、实验7-1Tomcat服务部署7-2Tomcat虚拟主......
  • vuedemo
    一.创建环境1.创建D:\code\vue文件夹2.vscode打开文件夹3.打开终端,输入npminstall-g@vue/cli4.配置环境变量终端输入:npmconfiglist找到路径将路径加入......
  • WindowsAPI示例-C#版_监控usb设备插拔
    1、Winform代码:publicpartialclassUSBDeviceMode:Form{publicUSBDeviceMode(){InitializeComponent();UsbN......
  • coredump配置、产生、分析以及分析示例
    应用程序在运行过程中由于各种异常或者bug导致退出,在满足一定条件下产生一个core文件。什么是coredump?通常情况下coredmp包含了程序运行时的内存,寄存器状态,堆栈指针,内存......
  • 交叉表应用示例
    createtableA(Namevarchar(10),Provincevarchar(20),Scoreint)insertAselect'李三','四川',5unionselect'小王','四川',3unionselect'小張','廣州',3uni......
  • Linux环境下配置vscode的C/C++ 的make编译环境(编写makefile方式)代码Demo版
    以前写过同样话题下的图文版的,这里给出一个代码Demo版本,上一个图文版本参见:​​Linux环境下配置vscode的C/C++的make编译环境(编写makefile方式)​​  ===================......
  • springboot openfeign服务端与客户端调用演示demo
    文章目录​​serverdemo演示​​​​创建server项目​​​​application.properties配置​​​​importjar[pom.xml]​​​​创建服务端的restfulcontroller​​​​验......
  • .NET导出示例【代码可直接使用】
    话不多说,上码查询结果集中对Model中的字段加属性[Description("字段中文注释")]publicstringName{get;set;}调用代码1//导出EXCEL2publicMem......