多线程使用实例

本文介绍了一种利用多线程技术高效处理大规模数据列表的方法。通过对数据进行平均分配,创建多个子任务并行处理,最后合并处理结果,显著提高了处理速度。文章详细展示了如何使用Java的ExecutorService和CompletionService实现这一过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值