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;
            }
    
        }
  • 相关阅读:
    cloudera cdh4 hue 安装
    设计模式Observer(观察者模式)
    编译android源码三(编译系统)
    centos 6.3 修改默认的系统语言
    Linux下查看文件和文件夹大小的df和du命令
    编译android源码二(下载源代码)
    devenv.exe
    Javascript和xml合用
    DataKeys的用法
    XSL(转)
  • 原文地址:https://www.cnblogs.com/zzq-include/p/13565447.html
Copyright © 2011-2022 走看看