Detailed explanation of @Async asynchronous function in Java
@Async annotation can implement the function of asynchronous processing. It can have a return value, or directly execute a task in parallel when a new thread. For asynchronous, its execution is conditional. You need to put the asynchronous code blocks in a separate class, so that when spring is injected, it will not affect each other, because asynchronous is a relatively special proxy.
Asynchronous portal
@EnableAsync
Specific asynchronous method
/** * The type of exception should be separated from the class executed synchronously, so that it will not interfere with each other when the ioc is established. */ @Service public class MessageService { @Async public void msg1() throws Exception { (5000L); ("async1:" + () + ",id:" + ().getId()); } }
The asynchronous in the above code is a return value, and generally this method can be used for sending messages.
Asynchronous with return value
@Async public Future<String> asyncMethodWithReturnType() { ("Execute method asynchronously - " + ().getName()); try { (5000); return new AsyncResult<String>("hello world !!!!"); } catch (InterruptedException e) { // } return null; }
This will return a delegate object Future. If we want to get its return, we need to listen to it in the main program, which is to write it in the loop and wait for its return result.
Future<String> future = (); while (true) { ///The loop judgment is used here, waiting to obtain the result information if (()) { //Discern whether the execution is completed ("Result from asynchronous process - " + ()); break; } ("Continue doing something else. "); ("main end:" + () + ",id:" + ().getId()); }
When the above code main program executes the asynchronous method, it will rent and block until there is a result returned.
This is the end of this article about the detailed explanation of @Async asynchronous function in Java. For more related content on @Async asynchronous function, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!