• Java 多线程均匀处理同一个List中的数据


    需求:使用多线程来处理同一个List中的数据,希望每个线程处理的数量是均匀的

    事例代码如下:

    public class Test {
        static class HandleThread extends Thread {
            private String threadName;
            private List<String> list;
            private int startIndex;
            private int endIndex;
    
            public HandleThread(String threadName, List<String> list, int startIndex, int endIndex) {
                this.threadName = threadName;
                this.list = list;
                this.startIndex = startIndex;
                this.endIndex = endIndex;
            }
    
            public void run() {
                List<String> subList = list.subList(startIndex, endIndex);
                System.out.println(threadName+"处理了"+subList.size()+"条!startIndex:"+startIndex+"|endIndex:"+endIndex);
            }
    
        }
    
        public static void main(String[] args) {
            Test test = new Test();
            List<String> tmpList = new ArrayList<String>();
            for (int i = 0; i < 120; i++) {
                tmpList.add("test" + i);
            }
    
            int length = tmpList.size();
            int num = 10; //初始线程数
    
            //启动多线程
            if(num > length){
                num = length;
            }
            int baseNum = length / num;
            int remainderNum = length % num;
            int end  = 0;
            for (int i = 0; i < num; i++) {
                int start = end ;
                end = start + baseNum;
                if(i == (num-1)){
                    end = length;
                }else if( i < remainderNum){
                    end = end + 1;
                }
                HandleThread thread = new HandleThread("线程[" + (i + 1) + "] ",  tmpList,start , end);
                thread.start();
            }
        }
    }

    控制台输出如下:

  • 相关阅读:
    Oracle 备份脚本
    Centos 安装DBI和ORACLE DBD
    人生到此初相见——北漂18年(10)
    备份上个月的日志
    mysql 授权
    竹杖芒鞋轻胜马,一蓑烟雨任平生——写在38岁生日
    haproxy 跨域访问:
    redis 配置说明
    vsftpd 500 OOPS: bad bool value in config file for: anon_world_readable_only
    vsftpd 配置虚拟用户
  • 原文地址:https://www.cnblogs.com/JoeyWong/p/9330039.html
Copyright © 2020-2023  润新知