Java 多线程处理一个List
答案:3 悬赏:80
解决时间 2021-02-15 03:26
- 提问者网友:烟刺痛了眼
- 2021-02-14 10:03
Java 多线程处理一个List
最佳答案
- 二级知识专家网友:单身小柠`猫♡
- 2021-02-14 10:23
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
public class Test_4 {
public synchronized void handleList(List 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 data;
private int start;
private int end;
public HandleThread(String threadName, List data, int start, int end) {
this.threadName = threadName;
this.data = data;
this.start = start;
this.end = end;
}
public void run() {
// TODO 这里处理数据
data.subList(start, end).add("^&*");
System.out.println(threadName)
}
}
public static void main(String[] args) {
Test_4 test = new Test_4();
// 准备数据
List data = new ArrayList();
for (int i = 0; i < 5000; i++) {
data.add("item" + i);
}
test.handleList(data, 5);
System.out.println(ArrayUtils.toString(data));
}
}
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
public class Test_4 {
public synchronized void handleList(List
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
private int start;
private int end;
public HandleThread(String threadName, List
this.threadName = threadName;
this.data = data;
this.start = start;
this.end = end;
}
public void run() {
// TODO 这里处理数据
data.subList(start, end).add("^&*");
System.out.println(threadName)
}
}
public static void main(String[] args) {
Test_4 test = new Test_4();
// 准备数据
List
for (int i = 0; i < 5000; i++) {
data.add("item" + i);
}
test.handleList(data, 5);
System.out.println(ArrayUtils.toString(data));
}
}
全部回答
- 1楼网友:如果这是命
- 2021-02-14 11:51
把list分成五个局部的list,给五个线程处理把
- 2楼网友:星星坠落
- 2021-02-14 10:46
多线程并发操作,
请使用Collections.synchronizedList(new LinkedList());
这样就是线程安全
另外LinkedList插入快
再次就是启动jvm的参数设置
-Xms512m Xmx1024m
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯