Java多線程的使用

字號:


    最近在項目里面使用了多線程處理技術,感覺對數(shù)據(jù)很多批量處理效果蠻好,所以在這里記錄下來,給自己一個日子,也分享給大家!
    1.首先根據(jù)條件得到你的數(shù)據(jù)集合dataList(此處用dataList表示)
    1.1個人覺得如果得到的數(shù)據(jù)很少的話,就沒必要使用多線程了
    2.用 int threadNum = Runtime.getRuntime().availableProcessors();得到你的cpu內核數(shù)
    2.1對于內核數(shù)這個來做下自己的說明,當時自己在做的時候,查看了一些對于使用cpu核數(shù)的文章
    有些高手做了一些性能方面的測試,表示當核數(shù)叫多的時候,處理性能提升很好,但更多的時候,已經(jīng)沒有那么明顯的效果了(好像記得那位高手借鑒了IBM的某個文章來說了的),這個大家可以另外去搜索查詢下,個人是以 4個為標準來做的,大家可以自尋決定
    3. 根據(jù)dataListSize 與 threadNum,來計算每個線程需要處理的數(shù)據(jù)量
    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一些說明
    大家可能問我這是要干什么,我來慢慢說明。由于數(shù)據(jù)集合 dataList 只有一個,但你需要做多線程處理,那怎么辦?根據(jù)cpu內核數(shù)(threadNum)把這個數(shù)據(jù)集合 dataList分成幾個 數(shù)據(jù)集合?
    不行了,性能太差了,直接根據(jù)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)
    //根據(jù)你的邏輯做自己的事啦
    。。。。。
    }
    return resultArray;
    }
    5.雖然結束了,但還需做一些說明
    5.1 在 MailCall這個方法里,由于是多線程,所以這個里面不能使用非線程安全共享的,比如
    simpleDateFormat,關于這個怎么去解決,
    (1)很多人都是用 apache的commons-lang包的DateUtils和DateFormatUtils類,這兩個類的方法是線程安全的。
    (2)直接在這個方法里面 new 一個simpleDateFormat的新對象(感覺不好,如果多了不很消耗性能,1000條數(shù)據(jù)不要new 1000個simpleDateFormat對象么。。。。。。。)
    (3)還有其它的就不說了,可自尋搜索啦