首页 > 编程语言 >java 多线程并行执行任务 demo

java 多线程并行执行任务 demo

时间:2022-12-30 15:00:43浏览次数:44  
标签:String thread demo List 并行执行 static new returnMap 多线程

package com.sleep.demo;

import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class MyThread {
    private static final int THREAD_SIZE = Integer.parseInt(System.getProperty("getRealPriceInfo.THREAD_SIZE", "20"));
    private static final long DEFAULT_TIMEOUT = Integer.parseInt(System.getProperty("getRealPriceInfo.defaultTimeout", "10000"));

    private static final ThreadPoolExecutor REAL_PRICE_EXECUTOR = new ThreadPoolExecutor(
            THREAD_SIZE, THREAD_SIZE, 30, TimeUnit.MINUTES, new LinkedBlockingDeque<>(), new ThreadFactory() {
        private final AtomicInteger count = new AtomicInteger(0);

        @Override
        public Thread newThread( Runnable r) {
            Thread thread = new Thread(r);
            thread.setDaemon(true);
            thread.setPriority(Thread.NORM_PRIORITY);
            thread.setName("getRealPriceInfo-" + count.incrementAndGet());
            return thread;
        }
    }, new ThreadPoolExecutor.CallerRunsPolicy());
    public static <T> List<List<T>> splitListBycapacity(List<T> source, int capacity) {
        List<List<T>> result = new ArrayList<List<T>>();
        if (source != null) {
            int size = source.size();
            if (size > 0) {
                for (int i = 0; i < size; ) {
                    List<T> value = null;
                    int end = i + capacity;
                    if (end > size) {
                        end = size;
                    }
                    value = source.subList(i, end);
                    i = end;
                    result.add(value);
                }

            } else {
                result = null;
            }
        } else {
            result = null;
        }

        return result;
    }
    public static void main(String[] args) {
        String skuIds = "1,2,3,4,5,6,7,8,9,10";
        String address="ddd";
        Map<String, Map<String, String>> returnMap = new HashMap<>();


        List<Long> skuList = Arrays.asList(skuIds.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        List<List<Long>> lists = splitListBycapacity(skuList, 3);
        List<String> splitGroup = new ArrayList<>();
        for (List<Long> list : lists) {
            String group = StringUtils.join(list, ",");
            splitGroup.add(group);
        }

        List<CompletableFuture<Map<String, Map<String, String>>>> futures = splitGroup.stream()
                .map(skuIdString -> CompletableFuture.supplyAsync(() -> {
                    try {
                        return queryRealPriceInfo3333(skuIdString, address);
                    } catch (Exception e) {

                        return null;
                    }
                }, REAL_PRICE_EXECUTOR))
                .collect(Collectors.toList());

        try {
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
                    .get(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        } catch (Exception e) {
            throw new RuntimeException("thread pool execute timeout", e);
        }

        for (CompletableFuture<Map<String, Map<String, String>>> future : futures) {
            Map<String, Map<String, String>> now = future.getNow(null);

            returnMap.putAll(now);

        }
        System.out.println(returnMap);
    }

    private static Map<String, Map<String, String>> queryRealPriceInfo3333(String skuIds, String address) {
        List<Long> skuList = Arrays.asList(skuIds.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());


        Map<String, Map<String, String>> returnMap = new HashMap<>();



        for (Long sku : skuList) {
            Map<String, String> chiled1 = new HashMap<>();
            chiled1.put("a1","a1");
            chiled1.put("b1","b1");
            chiled1.put("c1","c1");
            returnMap.put(sku+"",chiled1);
        }

        System.out.println(returnMap);
        return  returnMap;
    }

}

 


 

标签:String,thread,demo,List,并行执行,static,new,returnMap,多线程
From: https://www.cnblogs.com/niun/p/17014886.html

相关文章

  • 【Worker】js使用多线程实现倒计时
    tremaintime.js主要用于计算时间,放到assets目录,因为Worker需要请求获取这个文件的,要同源onmessage=function({data}){setInterval(()=>{postMessage(ini......
  • JavaScript如何实现多线程?
    我们都知道JS是一种单线程语言,即使是一些异步的事件也是在JS的主线程上运行的。像setTimeout、ajax的异步请求,或者是dom元素的一些事件,都是在JS主线程执行的,这些操作并没有......
  • Python计算长方形面积(带参数函数demo)
    #计算面积函数defarea(width,height):returnwidth*heightdefprint_welcome(name):print("Welcome",name)print_welcome("duhuifeng")w=int(in......
  • Python if语句Demo
    num=int(input("请输入你的数字:"))if(num<3):print(num+2)elif(num>4andnum<6):print("好吧")else:print("还好")结果: 主要就是逻辑运......
  • Python lambda函数demo
    #匿名函数lambda'''lambda函数使用方法:lambdapamr1,pamr2:functionpamr1/parm2代表是参数function指的是实现逻辑'''#声明函数sum=lambdaarg1,arg2:arg......
  • Java线程创建形式 Thread构造详解 多线程中篇(五)
    深入解读Java线程的创建本质,本文对线程的创建进行了深入的分析与解读,不同于你以往看到的绝大多数线程创建文章Thread作为线程的抽象,Thread的实例用......
  • Error creating bean with name 'demoService': Scope 'request' is not active for t
    测试Spring作用域,@Scope(value=WebApplicationContext.SCOPE_REQUEST),启动报错Causedby:org.springframework.beans.factory.support.ScopeNotActiveException:Error......
  • MM SD 常用BAPI DEMO列表
    下面是最近这段时间整理的MMSD常用BAPI的demo。暂时先整理这些,后面关于什么盘点,预留等等的吧再慢慢追加吧。最近忙。忙完这阵再整理其他模块的BAPI。目前是想整理完BAPId......
  • 最近的ALV DEMO整理
    申请时请提供:地区-模块-昵称(如BJ-ABAP-XX)所有群管理严格,严格禁止一切外来链接、招聘、广告等垃圾信息!最近一段时间做的ALVdemo1​​ALVdemo 01:cl_salv_table简单输出......
  • 使用Py的多线程爬取P站,老司机慎入。
    hello呀,小伙伴们,今个给大家带来的是爬取P站的教程,别搞错,这个不是你想的那个p站。这样想肯定是你用黄黄的思想点进来的。众所周知,P站是个插画网站,也包含一些R18的插画。停停......