【轉載】JAVA多線程讀取、操做List集合

本文轉載自:http://blog.csdn.net/wang1989cs/article/details/47663565java

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;

public class Test_4 {
    /**
     * 多線程處理list
     *
     * @param data  數據list
     * @param threadNum  線程數
     */
    public synchronized void handleList(List<String> data, int threadNum) {
        int length = data.size();
        int tl = length % threadNum == 0 ? length / threadNum : (length
                / threadNum + 1);
 
        for (int i = 0; i < threadNum; i++) {
            int end = (i + 1) * tl;
            HandleThread thread = new HandleThread("線程[" + (i + 1) + "] ",  data, i * tl, end > length ? length : end);
            thread.start();
        }
    }
 
    class HandleThread extends Thread {
        private String threadName;
        private List<String> data;
        private int start;
        private int end;
 
        public HandleThread(String threadName, List<String> data, int start, int end) {
            this.threadName = threadName;
            this.data = data;
            this.start = start;
            this.end = end;
        }
 
        public void run() {
            // TODO 這裏處理數據
            List<String> subList = data.subList(start, end)/*.add("^&*")*/;
            System.out.println(threadName+"處理了"+subList.size()+"條!");
        }
 
    }
 
    public static void main(String[] args) {
        Test_4 test = new Test_4();
        // 準備數據
        List<String> data = new ArrayList<String>();
        for (int i = 0; i < 6666; i++) {
            data.add("item" + i);
        }
        test.handleList(data, 5);
        System.out.println(ArrayUtils.toString(data));
    }
}

相關文章:java.util.List接口的方法subList()的使用注意事項apache

List集合存儲是否有上限?多線程

答:(硬件內存因素暫不考慮)那就應該沒有上限,由於它的add()方法在JAVA DOC的解釋裏面,沒有容量的約束。可是,有一點,它的size()方法說返回列表中的元素數。若是列表包含多於 Integer.MAX_VALUE 個元素,則返回 Integer.MAX_VALUE。那麼就是說,若是容量超過 Integer.MAX_VALUE,就沒法用get(int index)獲得,由於get的參數範圍上限就是Integer.MAX_VALUE。此時只能用iterator()去訪問了,不過這時的應用應該沒什麼意義了(再去每一個元素比較,找到想要的嗎,顯然很累),因此,從這種意義上講Integer.MAX_VALUE能夠說是list的上限this

相關文章
相關標籤/搜索