springboot异步线程

springboot 异步线程使用

文章目录

  • springboot 异步线程使用
    • @EnableAsync 启动类添加注解
  • 异步线程池
    • 编写线程池配置类
    • 使用@Async 注解

@EnableAsync 启动类添加注解

@Service
public class AsyncService {
  
  	//标记异步方法
    @Async
    public void asyncMethod() throws InterruptedException {
      //调用业务方法
        T();
    }
    private void T() throws InterruptedException {
        TimeUnit.SECONDS.sleep(2);
        System.out.println("方法执行");
    }
}
@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;

    @GetMapping("test1")
    void asyn() throws InterruptedException {
        System.out.println(System.currentTimeMillis() );
        asyncService.asyncMethod();
        System.out.println( System.currentTimeMillis());
    }
}

结果:

1650532363726
1650532363745
方法执行

异步线程池

编写线程池配置类

@Configuration
public class AysncConfigPool {

    @Bean
    public ThreadPoolTaskExecutor asyncPoolTaskExecutor(){
        //创建线程池
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        //核心线程数量(默认1)
        pool.setCorePoolSize(10);
        //线程池维护的最大线程数
        pool.setMaxPoolSize(20);
        //缓存队列,等待线程数
        pool.setQueueCapacity(20);
        //超出核心线程,空闲时最大存活 时间 单位 秒
        pool.setKeepAliveSeconds(60);
        //线程名
        pool.setThreadNamePrefix("asyncThread");
        // 是不是等待所有线程执行完毕才关闭线程池,默认时false
        pool.setWaitForTasksToCompleteOnShutdown(true);
        // 等待 任务完成关闭的时长,默认时0,不等待
        pool.setAwaitTerminationSeconds(60);
        // 没有线程可被使用时的处理策略(任务拒绝策略)
        pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        pool.initialize();
        return pool;
    }
}

拒绝策略 效果
CallerRunsPolicy 线程满了,直接丢弃任务
abortPolicy 抛出 java util.concurrent.RejectedExecution
discardOldestPolicy 抛弃线程池中最后一个要执行的任务,并执行新任务
discardPolicy 不做任何操作

使用@Async 注解

@Service
public class AsyncService {

    // 异步线程池
    @Async("asyncPoolTaskExecutor")
    public void poolMethod(){
        //打印线程名,和随机数
        System.out.println( Thread.currentThread().getName() + Math.random());
    }
}
@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;

    @GetMapping("pool")
    public void pool(){
        System.out.println("主线程访问");
        for (int i = 0; i < 10; i++) {
            asyncService.poolMethod();
        }
        System.out.println("访问结束");
    }
}

结果:

主线程访问
访问结束
asyncThread100.4282493403434967
asyncThread30.22630021307065995
asyncThread70.585942312671337
asyncThread80.06514235429941129
asyncThread60.14317974751830398
asyncThread10.7365408244799241
asyncThread90.24699299199076785
asyncThread40.9734939500320485
asyncThread50.6961392436462727
asyncThread20.03074026258649787

你可能感兴趣的:(springBoot,spring)