SpringBoot_Async_异步调用

方法上使用@Async注解

@Component
public class Tasks{
    //定义一个随机对象.
    public static Random random = new Random();
    @Async
    public void taskOne() throws InterruptedException{
        System.out.println("开始做任务一");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
    }
    
    @Async
    public void taskTwo() throws InterruptedException{
        System.out.println("开始做任务二");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
    }
    
    @Async
    public void taskThree() throws InterruptedException{
        System.out.println("开始做任务三");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
    }
}

启动上使用注解@EnableAsync

你可能感兴趣的:(SpringBoot_Async_异步调用)