springboot异步线程

springboot 异步线程使用

@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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值