springboot自定义线程池,CompletableFuture实现多线程并发

创建线程池的四种方式

Executors.newCachedThreadPool() 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程

newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。

newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

阿里规约:
【强制】线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式,
这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。

关于ThreadPoolExecutor 和 ThreadPoolTaskExecutor 区别

ThreadPoolExecutor是一个java类不提供spring生命周期和参数装配。

ThreadPoolTaskExecutor实现了InitializingBean, DisposableBean ,xxaware等,具有spring特性

 简单理解:

1ThreadPoolTaskExecutor使用ThreadPoolExecutor并增强,扩展了更多特性

2ThreadPoolTaskExecutor只关注自己增强的部分,任务执行还是ThreadPoolExecutor处理。

3、前者spring自己用着爽,后者离开spring我们用ThreadPoolExecutor爽。

注意:ThreadPoolTaskExecutor 不会自动创建ThreadPoolExecutor需要手动调initialize才会创建
如果@Bean 就不需手动,会自动InitializingBean的afterPropertiesSet来调initialize

本文使用spring的ThreadPoolTaskExecutor

一、自定义线程池

@Configuration
public class ThreadPoolConfig {
    // 核心线程数
    private int corePoolSize = 5;
    // 最大线程数
    private int maxPoolSize = 10;
    // 队列大小
    private int queueSize = 100;
    // 线程最大空闲时间
    private int keepAliveSeconds = 100;
    /**
     * 自定义消费队列线程池
     * CallerRunsPolicy 这个策略重试添加当前的任务,他会自动重复调用 execute() 方法,直到成功。
     * AbortPolicy 对拒绝任务抛弃处理,并且抛出异常。
     * DiscardPolicy 对拒绝任务直接无声抛弃,没有异常信息。
     * DiscardOldestPolicy 对拒绝任务不抛弃,而是抛弃队列里面等待最久的一个线程,然后把拒绝任务加到队列。
     * @return
     */
    @Bean(value = "testThreadPool")
    public ThreadPoolTaskExecutor buildFirstThreadPool() {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        threadPool.setCorePoolSize(corePoolSize);
        threadPool.setMaxPoolSize(maxPoolSize);
        threadPool.setQueueCapacity(queueSize);
        threadPool.setThreadNamePrefix("testThreadPool-");
        threadPool.setKeepAliveSeconds(keepAliveSeconds);
        threadPool.setRejectedExecutionHandler(newThreadPoolExecutor.CallerRunsPolicy());
        //如果@Bean 就不需手动,会自动InitializingBean的afterPropertiesSet来调initialize
//      threadPool.initialize();
        return threadPool;
    }

}

二、具体逻辑实现

@RequestMapping("/test")
    public String test(){
        System.out.println("请求接口开始----->"+ LocalDateTime.now());
        CompletableFuture<Void> task1 = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("task1 线程name-->" + Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, taskExecutor);
        CompletableFuture<Void> task2 = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(2000);
                System.out.println("task2 线程name-->" + Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, taskExecutor);
        try {
            CompletableFuture.allOf(task1, task2).get();
            System.out.println("请求接口结束----->"+ LocalDateTime.now());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }

此外,多个任务可封装多个Runable 类,创建TaskList

//task任务
private class Task implements Runnable{
	@Override
        public void run() {
        //具体业务
        }
}
Task task1 = new Task();
Task task2 = new Task();

List<Runnable> taskList = new ArrayList<>();
        taskList.add(task1);
        taskList.add(task2);
CompletableFuture<?>[] futures = taskList.stream().map(e -> CompletableFuture.runAsync(e, customExecutor))
                .collect(Collectors.toSet()).toArray(new CompletableFuture[]{});
CompletableFuture.allOf(futures).get();
  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

音乐土豆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值