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 ykp * @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; } }
多线程使用实例
最新推荐文章于 2022-06-27 20:19:52 发布