您好,登錄后才能下訂單哦!
這篇文章主要講解了“編程中多線程的使用方法”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“編程中多線程的使用方法”吧!
ptn多線程使用實例:
在ptn項目中由于網(wǎng)管系統(tǒng)抓取的tunnel數(shù)據(jù)量較大,每條tunnel都需要做相對于的業(yè)務(wù)處理, 傳統(tǒng)的for循環(huán)方式中每一個tunnel去依次執(zhí)行,效率很慢
現(xiàn)將大的tunnerl list拆分為n個list ,每個list都是一個線程,提高效率;
詳情如下:
jdk 自帶線程池結(jié)果管理器:ExecutorCompletionService 它將BlockingQueue 和Executor 封裝起來。然后使用ExecutorCompletionService.submit()方法提交任務(wù)。
1.新建線程池
ExecutorService exs = Executors.newFixedThreadPool(analysisThreadNum);
2.線程池管理器,可以獲取多線程處理結(jié)果
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.合并多線程處理結(jié)果
for (int i = 1, curr = 0, length = futureList.size(); i <= length; i++) {
// 采用completionService.take(),內(nèi)部維護阻塞隊列,任務(wù)先完成的先獲取到
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.關(guān)閉線程池
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");//設(shè)置日期格式
Date now = new Date(); String startTime = sdf.format(now);
System.out.println("執(zhí)行開始時間"+startTime);
//準備數(shù)據(jù)
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 制造耗時的現(xiàn)象
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) {
//分開執(zhí)行任務(wù)
futureList.add(completionService.submit(new strAppendTask(strings)));
}
//合并處理結(jié)果
for (int i = 1,curr=0,length=futureList.size(); i <=length; i++) {
// 采用completionService.take(),內(nèi)部維護阻塞隊列,任務(wù)先完成的先獲取到
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("執(zhí)行結(jié)束時間"+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,主要通過偏移量來實現(xiàn)的
*
* @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; // (先計算出余數(shù))
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;
}
}
感謝各位的閱讀,以上就是“編程中多線程的使用方法”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對編程中多線程的使用方法這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。