Spring boot 2.0 multithreading concurrent task execution

In spring boot 2.0, there are two ways to execute multithreading. One is to directly inherit the parent class Thread or implement the Runnable interface class and override the run method. The other is to annotate @ Async through the support of spring boot.

First, the custom class inherits the Thread class or the Runnnable interface, overriding the run method

import com.xxx.xx.taskphone.model.PhoneCallin;
import com.xxx.xxx.taskphone.service.PhoneCallinService;

public class PhoneCallInThread implements Runnable{

	private PhoneCallinService phoneCallinService;
	public PhoneCallInThread(PhoneCallinService phoneCallinService) {
		this.phoneCallinService = phoneCallinService;
	public void run() {
        //phoneCallinService.test(); custom logical business

Open thread

public class TaskScheduling {

	private PhoneCallinService phoneCallinService;

	@Scheduled(fixedRate = 2000)
	public void savePhoneCallin(){
		long size = 5;
			new Thread(new PhoneCallInThread(phoneCallinService)).start();


Note: because thread processing is logical, spring cannot annotate the proxy class object (such as phoneCallInService); however, you can get the proxy object by getting the ApplicationSpringContext context context.

The scheduled task @ scheduled(fixedRate = 2000) I use here is executed every 2 seconds.

Second, springboot2.0 uses @ Async for asynchronous calls

Multithreaded configuration class

package com.xxx.perform.config;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

public class TaskPoolConfig {
	public Executor taskExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(10);//Number of core threads
		executor.setMaxPoolSize(20);//Specify the maximum number of threads
		executor.setQueueCapacity(200);//Maximum number in queue
		executor.setKeepAliveSeconds(60);//Maximum thread lifetime after idle
		executor.setThreadNamePrefix("taskExecutor-");//Thread name prefix
		executor.setWaitForTasksToCompleteOnShutdown(true);//When the thread pool is closed, wait for all tasks to be completed, and then continue to destroy other beans to ensure that the destruction of asynchronous tasks will precede the destruction of database connection pool objects.
		executor.setAwaitTerminationSeconds(60);//Set the wait time for tasks in the thread pool
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		return executor;

Enable thread support on startup class

public class PerformAdminApplication {

	public static void main(String[] args) {
		SpringApplication.run(AdminApplication.class, args);

The @ Async annotation indicates that the current class or current party is a thread class, and supports multithreading

@Scheduled(fixedRate = 2000)
public void test(){

Note that if a method annotated by @ Async is called multiple times, a thread will be generated to handle the method logic each time. In this way, we need to deal with the logical results in time. The return processing logic of the method needs to be provided.

Multithreaded asynchronous callback

Provide callback information class in the method marked as thread processing

public Future<String> doTaskCallback() throws Exception {
    return new AsyncResult<>("Task 2 completed");

Then get the return value directly and normally

List<String> result = new Test().doTaskCallback();

Finally, I suggest that we judge whether the current thread has completed before the next call, result.isDone(). If the thread does not end, you can Thead.sleep(1000), sleep for a certain time and execute again.

Published 21 original articles, won praise 2, 10000 visitors+
Private letter follow

Tags: Spring Java Database

Posted on Tue, 14 Jan 2020 00:02:04 -0500 by merylvingien