网站首页  汉语字词  英语词汇  考试资料  写作素材  旧版资料

请输入您要查询的范文:

 

标题 Java多线程的使用
范文
    最近在项目里面使用了多线程处理技术,感觉对数据很多批量处理效果蛮好,所以在这里记录下来,给自己一个日子,也分享给大家!
    1.首先根据条件得到你的数据集合dataList(此处用dataList表示)
    1.1个人觉得如果得到的数据很少的话,就没必要使用多线程了
    2.用 int threadNum = Runtime.getRuntime().availableProcessors();得到你的cpu内核数
    2.1对于内核数这个来做下自己的说明,当时自己在做的时候,查看了一些对于使用cpu核数的文章
    有些高手做了一些性能方面的测试,表示当核数叫多的时候,处理性能提升很好,但更多的时候,已经没有那么明显的效果了(好像记得那位高手借鉴了IBM的某个文章来说了的),这个大家可以另外去搜索查询下,个人是以 4个为标准来做的,大家可以自寻决定
    3. 根据dataListSize 与 threadNum,来计算每个线程需要处理的数据量
    3.1 相关代码
    int threadListSize = dataListSize;
    if(listSize<threadNum)
    {
    threadNum=1;
    }
    else if(threadNum>4)
    {
    threadNum=4;
    threadListSize = listSize / threadNum;
    }
    else
    {
    threadListSize = listSize / threadNum;
    }
    final int[] dataRange = new int[threadNum];
    for (int i = 0; i < threadNum - 1; i++) {
    dataRange[i] = threadListSize * (i + 1);
    }
    //有些不可能一下子除断,所以最后一个dataRange必须包含剩下所有的
    dataRange[threadNum - 1] = listSize;
    3.2一些说明
    大家可能问我这是要干什么,我来慢慢说明。由于数据集合 dataList 只有一个,但你需要做多线程处理,那怎么办?根据cpu内核数(threadNum)把这个数据集合 dataList分成几个 数据集合?
    不行了,性能太差了,直接根据list的索引来做啦,比如list.get(0),直接把索引分成对应的几个部分,然后dataList直接调用
    4.开始多线程啦
    4.1 相关代码
    4.1.1第一部分
    ExecutorService executor = Executors.newFixedThreadPool(threadNum);
    Future<JSONArray>[] results = new Future[threadNum];
    for (int i = 0; i < threadNum; i++) {
    int startIndex=0;
    if(i!=0)
    {
    startIndex=dataRange[i-1];
    }
    results[i]=executor.submit(new CounterTask(startIndex, dataRange[i]));
    }
    //每个线程处理完了之后,就会把对应返回的结果返回到 Future<JSONArray>[]
    JSONArray resultArray=new JSONArray();
    for(int i = 0; i < threadNum; i++)
    {
    resultArray.addAll(results[i].get());
    }
    //这个不要忘了
    executor.shutdown();
    4.1.2 第二部分(这个可以直接作为内部类来处理,不必外建一个类)
    class CounterTask implements Callable<JSONArray>{
    private int startIndex;
    private int endIndex;
    public CounterTask(int startIndex,int endIndex){
    this.startIndex=startIndex;
    this.endIndex=endIndex;
    }
    @Override
    public JSONArray call() throws Exception {
    // TODO Auto-generated method stub
    return MailCall(startIndex,endIndex);
    }
    }
    4.1.3 第三部分代码
    protected JSONArray MailCall(int startIndex,int endIndex) {
    JSONArray resultArray=new JSONArray();
    JSONObject result=null;
    for(int i=startIndex;i<endIndex;i++)
    {
    Object object=dataList.get(i)
    //根据你的逻辑做自己的事啦
    。。。。。
    }
    return resultArray;
    }
    5.虽然结束了,但还需做一些说明
    5.1 在 MailCall这个方法里,由于是多线程,所以这个里面不能使用非线程安全共享的,比如
    simpleDateFormat,关于这个怎么去解决,
    (1)很多人都是用 apache的commons-lang包的DateUtils和DateFormatUtils类,这两个类的方法是线程安全的。
    (2)直接在这个方法里面 new 一个simpleDateFormat的新对象(感觉不好,如果多了不很消耗性能,1000条数据不要new 1000个simpleDateFormat对象么。。。。。。。)
    (3)还有其它的就不说了,可自寻搜索啦
随便看

 

在线学习网范文大全提供好词好句、学习总结、工作总结、演讲稿等写作素材及范文模板,是学习及工作的有利工具。

 

Copyright © 2002-2024 cuapp.net All Rights Reserved
更新时间:2025/5/18 8:55:37