@Async通过配置线程池实现异步

在项目中有很多地方需要实现异步,@Async是一种比较简单的实现方式。
一、通过线程池配置
1、初始化线程池

@EnableAsync
@Configuration
@PropertySource("classpath:conf/core_thread.properties")
public class TaskPoolConfig {
    @Value("${core.pool.size}")
    private Integer corePooleSize;
    @Value("${max.pool.size}")
    private Integer maxPooleSize;
    @Value("${queue.capacity}")
    private Integer queueCapacity;
    @Value("${alive.time}")
    private Integer aliveTime;


    @Bean("taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePooleSize);
        executor.setMaxPoolSize(maxPooleSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(aliveTime);
        executor.setThreadNamePrefix("taskExecutor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}

2、设置配置线程的配置

core.pool.size=10
max.pool.size=10
queue.capacity=200
alive.time=60

3、配置异步方法

@Component
public class AsyncTask {
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    @Async("taskExecutor")
    public void doTaskOne(String aa) throws Exception {
        System.out.println("开始做任务一"+formatter.format(LocalDateTime.now())+aa);
        long start = System.currentTimeMillis();
        Thread.sleep(5000);
        long end = System.currentTimeMillis();
        System.out.println("完成任务一,耗时:" + (end - start) + "毫秒"+formatter.format(LocalDateTime.now())+aa);
    }
}

4、将异步方法类注入方法,调用注入异步类的中异步方法

 @Autowired
    private AsyncTask asyncTask;
    @Autowired
    private OrderService orderService;

    @RequestMapping("/page")
    @AnnDemo(value = "page")
    public List<Province> findPage(@RequestParam("username") String username) throws Exception {
        asyncTask.doTaskOne("eee");
        System.out.println("sdfffffff+"+formatter.format(LocalDateTime.now()));
        List<Province> listPage=orderService.getProvinces();
        System.out.println("sdfffffffkkkkk+"+formatter.format(LocalDateTime.now()));
        return listPage;
    }

查看执行结果

开始做任务一2019-09-19 21:38:35eee
sdfffffff+2019-09-19 21:38:35
2019-09-19 21:38:35.733  INFO 38688 --- [nio-8080-exec-2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-09-19 21:38:36.068  INFO 38688 --- [nio-8080-exec-2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
sdfffffffkkkkk+2019-09-19 21:38:36
完成任务一,耗时:5000毫秒2019-09-19 21:38:40eee

二、不用配置线程池的方式

1、配置异步方法

@Component
public class AsyncTask {
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    @Async
    public void doTaskOne(String aa) throws Exception {
        System.out.println("开始做任务一"+formatter.format(LocalDateTime.now())+aa);
        long start = System.currentTimeMillis();
        Thread.sleep(5000);
        long end = System.currentTimeMillis();
        System.out.println("完成任务一,耗时:" + (end - start) + "毫秒"+formatter.format(LocalDateTime.now())+aa);
    }
}

2、将异步方法类注入方法,调用注入异步类的中异步方法

   @RequestMapping("/page")
    @AnnDemo(value = "page")
    public List<Province> findPage(@RequestParam("username") String username) throws Exception {
        asyncTask.doTaskOne("eee");
        System.out.println("sdfffffff+"+formatter.format(LocalDateTime.now()));
        List<Province> listPage=orderService.getProvinces();
        System.out.println("sdfffffffkkkkk+"+formatter.format(LocalDateTime.now()));
        return listPage;
    }

查看执行结果

sdfffffff+2019-09-19 22:00:35
开始做任务一2019-09-19 22:00:35eee
2019-09-19 22:00:35.989  INFO 34372 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-09-19 22:00:36.293  INFO 34372 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
sdfffffffkkkkk+2019-09-19 22:00:36
完成任务一,耗时:5001毫秒2019-09-19 22:00:40eee
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值