多线程场景下-数据分片

多线程场景下实现平均切分数据,其实就是根据偏移量来计算每个线程要处理的数据大小,以下为测试场景

自己实现

public static void main(String[] args) {
        List<Integer> integerArrayList = new ArrayList<>();
        for (int i = 0; i < 1022; i++) {
            integerArrayList.add(i);
        }

        //总数据量
        int size = integerArrayList.size();
        int threadCount = 8;

        // 每一个线程处理的数据个数
        int taskCount = size / threadCount;

        for (int i = 0; i < threadCount; i++) {
            // 每一个线程任务数据list
            List<Integer> subData = null;
            if (i == (threadCount - 1)) {
                subData = integerArrayList.subList(i * taskCount, size);
            } else {
                subData = integerArrayList.subList(i * taskCount, (i + 1) * taskCount);
            }

            System.out.println(i+"-->Size: "+subData.size());
        }

    }

测试结果:

0-->Size: 127
1-->Size: 127
2-->Size: 127
3-->Size: 127
4-->Size: 127
5-->Size: 127
6-->Size: 127
7-->Size: 133

API实现

import com.google.common.collect.Lists;
import org.apache.commons.collections4.ListUtils;

import java.util.ArrayList;
import java.util.List;

public class ListSplitTest {

    public static void main(String[] args) {
        List<Integer> integerArrayList = new ArrayList<>();
        for (int i = 0; i < 1022; i++) {
            integerArrayList.add(i);
        }
        
        //apache.commons
        List<List<Integer>> partition = ListUtils.partition(integerArrayList, 100);
        for (List<Integer> list : partition) {
            System.out.println("size: "+list.size());
        }

        System.out.println("++++++++++++++++++++++++++++++++++++");
        //google.common
        List<List<Integer>> partition1 = Lists.partition(integerArrayList, 100);
        for (List<Integer> list : partition1) {
            System.out.println("size1: "+list.size());
        }
    }
}

测试结果:

size: 100
size: 100
size: 100
size: 100
size: 100
size: 100
size: 100
size: 100
size: 100
size: 100
size: 22
++++++++++++++++++++++++++++++++++++
size1: 100
size1: 100
size1: 100
size1: 100
size1: 100
size1: 100
size1: 100
size1: 100
size1: 100
size1: 100
size1: 22
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值