当你想使用JAVA的多线程对一个集合进行处理的时候,我们可以将一个集合分成Thread份数据,每份数据交给一个线程执行,一下例子为多线程发送post请求,可达到非常高的高并发,8个线程就会刷屏。按自己电脑配置调整。
public static StringBuffer multi2Post(List<String> list , final int threadNum){
int size = list.size();
if (size == 0){
return null;
}
String url = POSTEnum.QUERY_GOOD_DETAIL_URL.getValue()+DataPullUtils.getToken2();
String param = POSTEnum.QUERY_GOOD_DETAIL_PARAM.getValue();
JSONObject object = JSONObject.parseObject(param);
StringBuffer dataBuffer = new StringBuffer();
ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
List<Future<String>> futures = new ArrayList<Future<String>>();
int length = size / threadNum;
for (int i = 0; i < threadNum; i++) {
// final List<String> subList = list.subList(size / threadNum * i, size / threadNum * (i + 1));
List<String> subList = new ArrayList<>();
if (i != threadNum-1){
for (int j = length*i; j < length*(i+1); j++) {
subList.add(list.get(j));
}
}else{
for (int j = length*i; j < list.size(); j++) {
subList.add(list.get(j));
}
}
Callable<String> task =new Callable<String>() {
@Override
public String call() throws Exception {
StringBuffer buffer = new StringBuffer();
for (String str : subList) {
//DataPullUtils.doPost(url, object.toString()) post方法,需要用可以看我的博客中有具体代码跟jar包
String line = DataPullUtils.doPost(url, str);
//打印一下
log.info("line ========<><> " + line);
buffer.append(line);
}
//单个线程返回结果
return buffer.toString();
}
};
futures.add(executorService.submit(task));
}
for (int i = 0; i < futures.size(); i++) {
try {
//拼接各个线程返回的结果
dataBuffer.append(futures.get(i).get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
executorService.shutdown();
return dataBuffer;
}
将代码中的每份数据处理的逻辑改为想要处理的集合中的逻辑数据即可~
小哥哥小姐姐们可以帮忙点点赞哦~