instructions

Using the @async annotation to create multiple threads is very convenient and can be configured to implement thread pools. Much simpler than using thread pools directly. In addition, it is no different from ordinary methods in use, with an @async annotation to achieve asynchronous calls.

usage

AsyncTask.java

@Component
public class AsyncTask {
 private static final Logger LOG = LoggerFactory.getLogger(AsyncTask.class);
 @Async
 public void register(){
 LOG.info("Multithreading starts registration emulation");
 try {
 Thread.sleep(1000*1);
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 LOG.info("Multi-thread registration successful"); }}Copy the code

This is just a simple printout, printed using Log4J to make it easy to see the thread name

AsyncTaskController.java

@RestController
@RequestMapping(value = "/async")
public class AsyncTaskController {
 private final static Logger LOG = LoggerFactory.getLogger(AsyncTaskController.class);
 @Autowired
 private AsyncTask asyncTask;
 @GetMapping(value = "/test")
 public Object test() {for (int i = 0; i < 10; i++) {
 asyncTask.register();
 }
 System.out.println("End of main thread");
 return "OK"; }}Copy the code

This loop creates 10 threads

Enable the Async

Enabling Async requires the @enableAsync annotation

@SpringBootApplication @ServletComponentScan @EnableAsync public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); }}Copy the code

The results of

As you can see, the main thread termination has ended. There is proof that multithreading works. In addition, by looking at the thread name, you can see that 10 threads were created to execute.


Using thread pools

As you can see from the above results, using the @async annotation directly creates the thread to execute it. However, in practical development, thread pools should be used to manage threads and save thread overhead.

configuration

TaskExecutorConfig.class

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;

@Configuration
public class TaskExecutorConfig implements AsyncConfigurer {
 /**
 * Set the ThreadPoolExecutor's core pool size. */ private static final int CORE_POOL_SIZE = 2; /** * Set the ThreadPoolExecutor's maximum pool size.
 */
 private static final int MAX_POOL_SIZE = 2;
 /**
 * Set the capacity for the ThreadPoolExecutor's BlockingQueue. */ private static final int QUEUE_CAPACITY = 10; /** * The AsyncConfigurer interface is implemented by overriding the getAsyncExcutor method to specify the default task execution. And return a ThreadPoolTaskExevutor * so we get a TaskExecutor based thread pool */ @override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(CORE_POOL_SIZE); taskExecutor.setMaxPoolSize(MAX_POOL_SIZE); taskExecutor.setQueueCapacity(QUEUE_CAPACITY); taskExecutor.initialize(); return taskExecutor; }}Copy the code

A maximum of two threads are set here.

test

Restart the program to test:

The results of

You can see that only two threads are executing, proving that the configured thread pool is working.