我们在使用多线程的时候,往往需要创建Thread类,或者实现Runnable接口,如果要使用到线程池,我们还需要来创建Executors,在使用spring中,已经给我们做了很好的支持。只要要@EnableAsync就可以使用多线程。使用@Async就可以定义一个线程任务。通过spring给我们提供的ThreadPoolTaskExecutor就可以使用线程池。
定义配置类,如果不配置可直接将@EnableAsync注解加到启动类上面
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
public class ThreadPoolTaskConfig implements AsyncConfigurer {
private static final int corePoolSize = 5; // 核心线程数(默认线程数)
private static final int maxPoolSize = 10; // 最大线程数
private static final int keepAliveTime = 10; // 允许线程空闲时间(单位:默认为秒)
private static final int queueCapacity = 25; // 缓冲队列数
@Override
public Executor getAsyncExecutor() {
//线程池
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(corePoolSize);
taskExecutor.setMaxPoolSize(maxPoolSize);
taskExecutor.setKeepAliveSeconds(keepAliveTime);
taskExecutor.setQueueCapacity(queueCapacity);
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
service
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service
public class testAsyncService {
Logger log = LoggerFactory.getLogger(testAsyncService.class);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Async
public void service1() throws InterruptedException {
log.info("--------start-service1:"+ df.format(new Date()) +"------------");
Thread.sleep(5000); // 模拟耗时
log.info("--------end-service1:"+ df.format(new Date()) +"------------");
}
@Async
public void service2() throws InterruptedException {
log.info("--------start-service2:"+ df.format(new Date()) +"------------");
Thread.sleep(2000); // 模拟耗时
log.info("--------end-service2:"+ df.format(new Date()) +"------------");
}
}
controller
import com.example.demotest.service.testAsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class controller {
@Autowired
testAsyncService service;
@GetMapping("/get")
public void test() throws InterruptedException {
for(int i=0;i<3;i++) {
service.service1();
service.service2();
}
}
}
测试结果,可以看到并不是顺序执行,说明异步执行成功。