SpringBoot2.x asynchronous tasks

1. Start the class which annotations using @EnableAsync opening function, automatic scanning

 

2. In the method of the above plus @Async

 

I am here to write a test class

@Component
@Async
public class AsyncTask {
    public void task1() throws InterruptedException {
        long begin = System.currentTimeMillis();
        Thread.sleep(1000);
        long end = System.currentTimeMillis();
        long total = end - begin;
        System.err.println("任务1耗时:"+total);
    }

    public void task2() throws InterruptedException {
        long begin = System.currentTimeMillis();
        Thread.sleep(2000);
        long end = System.currentTimeMillis();
        long total = end - begin;
        System.err.println("任务2耗时:"+total);
    }

    public void task3() throws InterruptedException {
        long begin = System.currentTimeMillis();
        Thread.sleep(3000);
        long end = System.currentTimeMillis();
        long total = end - begin;
        System.err.println("任务3耗时:"+total);
    }
}

 

Then add a controller asynchronous method call this method the task

/*
* 异步任务
* */
@GetMapping("async_total")
public long AsyncTotal() throws InterruptedException {
    long begin  = System.currentTimeMillis();
    asyncTask.task1();
    asyncTask.task2();
    asyncTask.task3();
    long end = System.currentTimeMillis();
    long counttotal = end - begin;
    return counttotal;
}

If synchronization is where we need to spend a minimum of six seconds because I have three tasks to wait six seconds together

But I use asynchronous I ask this only took 2 seconds

Published 10 original articles · won praise 0 · Views 508

Guess you like

Origin blog.csdn.net/DNCCCC/article/details/105033852