zoukankan      html  css  js  c++  java
  • 多线程,计算List<Integer>

    /**
         * 多线程处理list
         *
         * @param data      数据list
         * @param threadNum 线程数
         */
        public static int handleList(List<Integer> data, int threadNum) {
            int length = data.size();
            int tl = length % threadNum == 0 ? length / threadNum : (length
                    / threadNum + 1);
            List<Future<Integer>> futureList = new ArrayList<>();
    
            for (int i = 0; i < threadNum; i++) {
                int end = (i + 1) * tl;
                ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
                Future<Integer> f = executorService.submit(new HandleThread("线程[" + (i + 1) + "] ", data, i * tl, end > length ? length : end));
                futureList.add(f);
            }
    
            int sum = 0;
    
            for (int i = 0; i < futureList.size(); i++) {
                try {
                    sum = sum + futureList.get(i).get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
    
            System.out.println(sum);
            return sum;
        }
    
        static class HandleThread implements Callable<Integer> {
            private String threadName;
            private List<Integer> data;
            private int start;
            private int end;
    
            public HandleThread(String threadName, List<Integer> data, int start, int end) {
                this.threadName = threadName;
                this.data = data;
                this.start = start;
                this.end = end;
            }
    
            public Integer call() {
                int sum = 0;
                List<Integer> subList = data.subList(start, end)/*.add("^&*")*/;
                for (int i = 0; i < subList.size(); i++) {
                    sum = sum + subList.get(i);
                }
                System.out.println(threadName + "处理了" + subList.size() + "条!");
                return sum;
            }
    
        }
  • 相关阅读:
    Vue.js-项目目录结构解析
    Vue.js-创建Vue项目(Vue项目初始化)并不是用Webstrom创建,只是用Webstrom打开
    Node.js-npm安装包目录修改
    Node.js-Webstorm2018配置nodejs
    Node.js-ReferenceError: _filename is not defined
    cas系列-自定义异常提示(五)
    cas系列-cas登出(四)
    cas系列-cas REST协议(三)
    maven引入第三方jar包
    持续api管理翻译
  • 原文地址:https://www.cnblogs.com/zzq-include/p/13565447.html
Copyright © 2011-2022 走看看