这篇文章主要讲解了“编程中多线程的使用方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“编程中多线程的使用方法”吧!
ptn多线程使用实例:
在ptn项目中由于网管系统抓取的tunnel数据量较大,每条tunnel都需要做相对于的业务处理, 传统的for循环方式中每一个tunnel去依次执行,效率很慢
现将大的tunnerl list拆分为n个list ,每个list都是一个线程,提高效率;
详情如下:
jdk 自带线程池结果管理器:ExecutorCompletionService 它将BlockingQueue 和Executor 封装起来。然后使用ExecutorCompletionService.submit()方法提交任务。
1.新建线程池
ExecutorService exs = Executors.newFixedThreadPool(analysisThreadNum);
2.线程池管理器,可以获取多线程处理结果
CompletionService<Map<String, Object>> completionService = new ExecutorCompletionService<>(exs);
3.将一个list切分为多个list 均分tunnullist
List<List<Tunnel>> averageAssign = CommUtils.averageAssign(tunnels, analysisThreadNum);
4.遍历averageAssign 均分list
List<Future<Map<String, Object>>> futureList = new ArrayList<>();
for (List<Tunnel> list : averageAssign) {
futureList.add(completionService.submit(new LogicPathOverlappedCheckTask(list, portNameLinkIdMap,tunnelClassifyMap, allNEs, allBoards, allTopoLines)));
}
5.合并多线程处理结果
for (int i = 1, curr = 0, length = futureList.size(); i <= length; i++) {
// 采用completionService.take(),内部维护阻塞队列,任务先完成的先获取到
Map<String, Object> result = completionService.take().get();
lineNumber += MapUtils.getInteger(result, "lineNumber", 0);
boardNumber += MapUtils.getInteger(result, "boardNumber", 0);
neNumber += MapUtils.getInteger(result, "neNumber", 0);
lineResultList.addAll((List<Map<String, Object>>) result.get("lineResultList"));
boardResultList.addAll((List<Map<String, Object>>) result.get("boardResultList"));
neResultList.addAll((List<Map<String, Object>>) result.get("neResultList"));
curr += MapUtils.getInteger(result, "listSize");
logger.debug("Thread : " + i + " is done. [" + curr + "/" + totailNumber+ "] tunnel logic path overlapped check is done ..");
}
6.关闭线程池
exs.shutdown();
package com.hongrant.www.comm.service.impl;
import com.hongrant.www.comm.util.DateUtils;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;
/**
* @author jy
* @date 2019/4/8 17:27
* ptn 逻辑同路由多线程使用借鉴
* 将一个list拆成多个list分别迭代处理每个list
*/
public class a {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
Date now = new Date(); String startTime = sdf.format(now);
System.out.println("执行开始时间"+startTime);
//准备数据
List<String> list = new ArrayList<>();
for (int i = 0; i <200000 ; i++) {
list.add("str:"+i+",");
}
// method1(list);
new a().method2(list);
}
public static void method1(List<String> list){
//将String全部拼接展示,记录所需时间
String b = "";
//使用String拼接而不用StringBuffer 制造耗时的现象
for (String s : list) {
b+=s;
}
System.out.println(b);
}
public void method2(List<String> list){
String str8="";
ExecutorService exs= Executors.newFixedThreadPool(6);
try {
CompletionService<String> completionService = new ExecutorCompletionService<>(exs);
List<Future<String>> futureList = new ArrayList<>();
//均分 List<String>
List<List<String>> avg=averageAssign(list,20);
for (List<String> strings : avg) {
//分开执行任务
futureList.add(completionService.submit(new strAppendTask(strings)));
}
//合并处理结果
for (int i = 1,curr=0,length=futureList.size(); i <=length; i++) {
// 采用completionService.take(),内部维护阻塞队列,任务先完成的先获取到
String s = completionService.take().get();
System.out.println("completion:"+s);
curr+=s.length();
str8+=s;
System.out.println("Thread :"+i+ "is done");
}
exs.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}finally {
if(!exs.isShutdown()){
exs.shutdown();
}
}
System.out.println("str8="+str8);
String endTime= DateUtils.getCurrentDateTime(DateUtils.DATE_TIME_FORMAT);
System.out.println("执行结束时间"+endTime);
}
static class strAppendTask implements Callable<String>{
private List<String > list;
public strAppendTask(List<String> strings){
this.list=strings;
}
@Override
public String call() throws Exception {
String b = "";
for (String s : list) {
b+=s;
}
System.out.println("处理完成str="+b);
return b;
}
}
/**
* 将一个list均分成n个list,主要通过偏移量来实现的
*
* @param source
* @return
*/
public static <T> List<List<T>> averageAssign(List<T> source, int n) {
List<List<T>> result = new ArrayList<List<T>>();
if (n == 1) {
result.add(source);
return result;
}
int remaider = source.size() % n; // (先计算出余数)
int number = source.size() / n; // 然后是商
int offset = 0;// 偏移量
for (int i = 0; i < n; i++) {
List<T> value = null;
if (remaider > 0) {
value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
remaider--;
offset++;
} else {
value = source.subList(i * number + offset, (i + 1) * number + offset);
}
result.add(value);
}
return result;
}
}
感谢各位的阅读,以上就是“编程中多线程的使用方法”的内容了,经过本文的学习后,相信大家对编程中多线程的使用方法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。