@Async注解

https://blog.csdn.net/zzzgd_666/article/details/82658832 

@EnableAsync
    @Configuration
    class TaskPoolConfig{
        @Bean("taskExecutor")
        public Executor taskExecutor(){
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(10);
            executor.setMaxPoolSize(20);
            executor.setQueueCapacity(200);
            executor.setKeepAliveSeconds(60);
            executor.setThreadNamePrefix("taskExecutor-");
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            return executor;
        }
    }
import java.util.Random;

/**
* 异步处理
*
* @author <a href="jian.huang@bintools.cn">yunzhe</a>
* @version 1.0.0 2019-07-09-上午11:19
*/
@Slf4j
@Component
public class Task {
   public static Random random = new Random();
   @Async("taskExecutor")
   public void doTaskOne() throws InterruptedException {
       log.info("开始任务一");
       long start = System.currentTimeMillis();
       Thread.sleep(random.nextInt(10000));
       long end = System.currentTimeMillis();
       log.info("完成任务一、耗时:"+(end-start)+"毫秒");
   }
   @Async("taskExecutor")
   public void doTaskTwo() throws InterruptedException {
       log.info("开始任务二");
       long start = System.currentTimeMillis();
       Thread.sleep(random.nextInt(10000));
       long end = System.currentTimeMillis();
       log.info("完成任务二、耗时:"+(end-start)+"毫秒");
   }
   @Async("taskExecutor")
   public void doTaskThree() throws InterruptedException {
       log.info("开始任务三");
       long start = System.currentTimeMillis();
       Thread.sleep(random.nextInt(10000));
       long end = System.currentTimeMillis();
       log.info("完成任务三、耗时:"+(end-start)+"毫秒");
   }
}    
/***
*
*/
@Component
@Slf4j
public class AsyncTask {
    @Async("taskExecutor")
    public Future<String> doTask() throws InterruptedException {
        log.info("Task1 started");
        long start = System.currentTimeMillis();
        Thread.sleep(5000);
        long end = System.currentTimeMillis();
        log.info("Task1 finished,time elapsed:{} ms",end-start);
        return new AsyncResult<>("Task1 accomplished");
    }
    @Async("taskExecutor")
    public Future<String> doTask2() throws InterruptedException {
        log.info("Task2 started");
        long start = System.currentTimeMillis();
        Thread.sleep(3000);
        long end = System.currentTimeMillis();
        log.info("Task2 finished,time elapsed:{} ms",end-start);
        return new AsyncResult<>("Task2 accomplished");
    }
}  

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值