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()的使用注意事项
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的上限