3.2 Spring高级话题: 多线程
3.2 Spring 多线程
1.Spring通过任务执行器(TaskExecutor)实现多线程和并发编程
2.使用ThreadPoolExecutor可以实现一个基于线程池的TaskExecutor
3.实际开发中是异步的 -> 需要在配置类中开启@EnableAsync注解
-> 在Bean中使用@Async注解来声明是一个异步任务
配置过程
1.通过@EnableAsync注解开启异步任务支持
2.通过java配置,返回一个ThreadPoolTaskExecutor(基于线程池的任务执行器)
3.通过@Async注解表明方法是异步方法,注入注解在类上就表明所有的方法都是异步方法
-> 这里的方法被注入的ThreadPoolTaskExecutor执行
1.java配置
package com.sgx.inspect.bug.service;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
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
@ComponentScan("com.sgx.inspect.bug")
@EnableAsync
public class ThreadPoolExecutorTaskConfigure implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(10);
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
2.使用@Async注解
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncTaskService {
@Async
public void asyncTask(int i) {
System.out.println("异步执行1:result:" + i);
}
@Async
public void asyncTask2(int i) throws InterruptedException {
Thread.sleep(10);
System.out.println("异步执行2:result:" + i);
}
public void syncTask(int i) {
System.out.println("同步执行1:result:" + i);
}
public void syncTask2(int i) throws InterruptedException {
Thread.sleep(10);
System.out.println("同步执行2:result:" + i);
}
}
3.测试使用
import com.sgx.inspect.bug.service.AsyncTaskService;
import com.sgx.inspect.bug.service.ThreadPoolExecutorTaskConfigure;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {
public static void main(String[] args) throws InterruptedException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ThreadPoolExecutorTaskConfigure.class);
AsyncTaskService bean = context.getBean(AsyncTaskService.class);
/**
* 支持同步方法
*/
for (int i = 0; i <= 10; i++) {
bean.syncTask(i);
bean.syncTask2(i);
}
/**
* 执行异步方法
*/
for (int i = 0; i <= 10; i++) {
bean.asyncTask(i);
bean.asyncTask2(i);
}
context.close();
}
}