SpringBoot实现线程池并结合CompletableFuture使用的简单示例

1.配置线程池

package com.demo.thread;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: mt
 * @description: say something....
 * @create: 15:16 2022/8/2
 */
@EnableAsync
@Configuration
public class ExecutorConfig {

    @Bean("taskExecutor")
    public Executor asyncServiceExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数:线程池创建时候初始化的线程数
        executor.setCorePoolSize(10);
        // 最大线程数:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        executor.setMaxPoolSize(10);
        // 缓冲队列:用来缓冲执行任务的队列
        executor.setQueueCapacity(500);
        // 允许线程的空闲时间60秒:当超过了核心线程之外的线程在空闲时间到达之后会被销毁
        executor.setKeepAliveSeconds(60);
        // 线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池
        executor.setThreadNamePrefix("test-thread-");
        // 缓冲队列满了之后的拒绝策略:由调用线程处理(一般是主线程)
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        executor.initialize();
        return executor;
    }
}

2.创建service接口,执行异步任务

package com.demo.thread;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

/**
 * @author: mt
 * @description: say something....
 * @create: 15:21 2022/8/2
 */
@Service
public class AsyncService {

    @Async("taskExecutor")
    public CompletableFuture<Long> executeAsync1() throws InterruptedException {
        System.out.println(1);
        Thread.sleep(6000);
        return CompletableFuture.completedFuture(1L);
    }

    @Async("taskExecutor")
    public CompletableFuture<Long> executeAsync2() throws InterruptedException {
        System.out.println(2);

        Thread.sleep(6000);
        return CompletableFuture.completedFuture(2L);
    }

    @Async("taskExecutor")
    public CompletableFuture<Long> executeAsync3() throws InterruptedException {
        System.out.println(3);

        Thread.sleep(6000);
        return CompletableFuture.completedFuture(3L);
    }

    @Async("taskExecutor")
    public CompletableFuture<Long> executeAsync4() throws InterruptedException {
        System.out.println(4);

        Thread.sleep(6000);
        return CompletableFuture.completedFuture(4L);
    }

    @Async("taskExecutor")
    public CompletableFuture<Long> executeAsync5() throws InterruptedException {
        System.out.println(5);

        Thread.sleep(6000);
        return CompletableFuture.completedFuture(5L);
    }

}

3.接口测试

@RequestMapping("/asyncTest")
    public String asyncTest(){
        try {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            CompletableFuture<Long> one = asyncService.executeAsync1();
            CompletableFuture<Long> two = asyncService.executeAsync2();
            CompletableFuture<Long> three = asyncService.executeAsync3();
            CompletableFuture<Long> four = asyncService.executeAsync4();
            CompletableFuture<Long> five = asyncService.executeAsync5();

            CompletableFuture.allOf(one,two,three,four,five);
            System.out.println(five.get());
            stopWatch.stop();
            double totalTimeSeconds = stopWatch.getTotalTimeSeconds();
            System.out.println("cost:"+totalTimeSeconds);
            System.out.println("get:"+five.get());


            return "success";
        }catch (Exception e) {
            return "error";
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值