springboot线程池底的使用

1.简单使用

一、配置类

@Configuration
@EnableAsync
public class SpringAsyncConfig {

    @Bean("taskExecutor")
    public Executor asyncServiceExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(5);
        // 设置最大线程数
        executor.setMaxPoolSize(20);
        //配置队列大小
        executor.setQueueCapacity(Integer.MAX_VALUE);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("xcc");
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //执行初始化
        executor.initialize();
        return executor;
    }
}

二、使用

public interfacr TestService{
      /**
     * 异步
     */
    void test();

    /**
     * 同步
     */
    void testThread();
}
@Service
public class TestServiceImpl implements TestService {
      @Async("taskExecutor")
    @Override
    public void test() {
        testThread();
    }


    @Override
    public void testThread(){
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

2.注解@async什么情况下失效

  • 1、注解@Async的方法不是public方法
  • 2、注解@Async的返回值只能为void或Future
  • 3、注解@Async方法使用static修饰也会失效
  • 4、没加注解@Async或EnableAsync注解,导致无法扫描到异步类
  • 5、调用方与被调用方不能再同一个类
  • 6、类中需要使用@Autowired或@Resource等注解自动注入,不能手动new对象
  • 7、在Async方法上标注@Transactional是没用的,但在Async方法调用的方法标注@Transcational是有效的
posted @ 2023-09-19 15:47  spiderMan1-1  阅读(37)  评论(0编辑  收藏  举报