码迷,mamicode.com
首页 > 其他好文 > 详细

并发请求合并返回实例

时间:2020-12-24 11:40:20      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:final   processor   ted   random   exception   cep   next   string   mys   

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class App3 {
    static Logger log = LoggerFactory.getLogger(App3.class);
    static int coreSize = getDefaultCoreSize();
    static int maxSize = coreSize * 2;
    static int keepAliveSeconds = 60;
    static BlockingQueue<Runnable> workQueue = new LinkedBlockingDeque<>();
    static final ExecutorService executorService = new ThreadPoolExecutor(coreSize,
            maxSize,
            keepAliveSeconds,
            TimeUnit.SECONDS,
            workQueue
    );

    public static void main(String[] args) throws Exception {
        log.info("开始执行");
        List<Future<List<String>>> tasks = new ArrayList<>();
        for (int i = 1; i <= 20; i++) {
            final int pageIdx = i;
            tasks.add(executorService.submit(() -> list(pageIdx)));
        }

        List<String> result = new ArrayList<>(1000);
        for (int i = 0; i < tasks.size(); i++) {
            result.addAll(tasks.get(i).get());
        }

        log.info("结果:{}",result.size());
        log.info("结果:{}",result);
    }

    private static List<String> list(int size) {
        int ms = ThreadLocalRandom.current().nextInt(100, 999);
        mySleep(ms);

        return IntStream.range(0, size)
                .mapToObj(p -> UUID.randomUUID().toString())
                .collect(Collectors.toList());
    }

    private static int getDefaultCoreSize() {
        return 2 * Runtime.getRuntime().availableProcessors();
    }

    private static void mySleep(int millsecond) {
        try {
            Thread.sleep(millsecond);
        } catch (InterruptedException eax) {
            eax.printStackTrace();
        }
    }
}

 

并发请求合并返回实例

标签:final   processor   ted   random   exception   cep   next   string   mys   

原文地址:https://www.cnblogs.com/zhshlimi/p/14158111.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!