Home >Java >javaTutorial >Introduction to springboot asynchronous calls (with code)

Introduction to springboot asynchronous calls (with code)

不言
不言forward
2019-04-12 10:33:153601browse

This article brings you an introduction to springboot asynchronous calls (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Synchronization

The programs are executed sequentially in the order defined. Each line of the program must wait for the completion of the previous line of program before it can be executed. That is, when a function call is issued, before the result is obtained, the program The call does not return.

Asynchronous

When the program is executed sequentially, the subsequent program is executed without waiting for the asynchronous call statement to return the result. When an asynchronous procedure call is issued, the caller cannot get the result immediately.

Synchronization code

Service layer:

public void test() throws InterruptedException {
       Thread.sleep(2000);
       for (int i = 0; i < 1000; i++) {
           System.out.println("i = " + i);
       }
   }

Controller layer:

   @GetMapping("test")
   public String test() {
       try {
           Thread.sleep(1000);
           System.out.println("主线程开始");
           for (int j = 0; j < 100; j++) {
               System.out.println("j = " + j);
           }
           asyncService.test();
           System.out.println("主线程结束");
           return "async";
       } catch (InterruptedException e) {
           e.printStackTrace();
           return "fail";
       }
   }

Request in browserhttp://localhost:8080/test
Console printing sequence:

  1. Start of main thread
  2. Print j loop
  3. Print i loop
  4. End of main thread

Asynchronous code

Add the @Async annotation to the test method of the Service layer, and at the same time add to the startup class in order for the asynchronous effect to take effect. @EnableAsyncAnnotation
Service layer:

   @Async
   public void test() throws InterruptedException {
       Thread.sleep(2000);
       for (int i = 0; i < 1000; i++) {
           System.out.println("i = " + i);
       }
   }

Controller remains unchanged, the startup class is added with @EnableAsync:

@SpringBootApplication
@EnableAsync
public class AsyncApplication {
    public static void main(String[] args) {
        SpringApplication.run(AsyncApplication.class, args);
    }
}

Request the printing sequence again as follows:

  1. Start of main thread
  2. Print j loop
  3. End of main thread
  4. Print i loop

The above is the detailed content of Introduction to springboot asynchronous calls (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete