SpringBoot @Async整合线程池

线程池配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
 * @author YanYu
 * @create 2021-02-01  10:28
 */
@EnableAsync
@Configuration
public class ThreadPoolConfig {

    /**
     * 线程核心数
     */
    private int corePoolSize = 10;
    /**
     * 线程最大数
     */
    private int maxPoolSize = 10;
    /**
     *任务容量
     */
    private int queueCapacity = 20;
    /**
     * 允许空闲时间,默认60
     */
    private int keepAlive = 100;

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        threadPoolTaskExecutor.setKeepAliveSeconds(keepAlive);
        threadPoolTaskExecutor.setThreadNamePrefix("Thread-");
        //设置拒绝策略 当线程数达到最大时,如何处理新任务
        //CallerRunsPolicy 不由线程池中线程执行,由调用者所在线程执行
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //所有任务完成后再关闭线程池
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        return threadPoolTaskExecutor;
    }
}

异步方法

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

/**
 * @author YanYu
 * @create 2021-02-01  10:43
 */
@Component
public class AsyncTaskTest {
    @Async("taskExecutor")
    public void print(String str){
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ":print " + str);
        }
    }
}

测试

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author YanYu
 * @create 2021-02-01  11:11
 */
@RestController
public class TestController {
    @Autowired
    AsyncTaskTest asyncTaskTest;
    @RequestMapping("/test")
    public void test(){
        asyncTaskTest.print("hello world");
    }
}

结果

连续访问几次发现不同的线程在打印hello world
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值