Use @Async and @EnableAsync to execute other methods asynchronously in the main thread

        Sometimes, we need to notify other interfaces after completing the logic in the method in one method, but return the result directly in the current method without waiting for other interfaces to return the result (for example, after the user has paid the order, the payment result needs to be returned to the user in time, and at the same time The merchant needs to be notified: the user has completed the payment), then an asynchronous call is required (the payment result is returned to the user without waiting for the merchant to be notified).

 

1. Add the @EnableAsync annotation to the startup class to indicate that the project supports asynchronous method calls;

2. Add the @Async annotation to the method that needs to be called asynchronously, indicating that the method is an asynchronous method, that is, the method and the caller are not in the same thread.

Sample code:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
public class AsyncDemoApplication {

    /**
     * async method
     *
     * @throws InterruptedException
     */
    @Async
    public void asyncMethod() throws InterruptedException {
        for (int i = 1; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + "********" + i);
        }
    }

    public static void main(String[] args) {

        try {
            //get context
            ConfigurableApplicationContext context = SpringApplication.run(AsyncDemoApplication.class, args);

            / / Get the object bean, and then call the asynchronous method
            context.getBean(AsyncDemoApplication.class).asyncMethod();
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "********" + i);
                if (2 == i)
                    Thread.sleep(1000l);
            }
        } catch (InterruptedException e) {
            e.printStackTrace ();
        }
    }
}

结果如下:
main********0
main********1
main********2
SimpleAsyncTaskExecutor-1********1
SimpleAsyncTaskExecutor-1********2
SimpleAsyncTaskExecutor-1********3
SimpleAsyncTaskExecutor-1********4
main********3
main********4

It can also be seen from the results that the asyncMethod method and the main thread are executed asynchronously.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325195397&siteId=291194637