最简单的Runnable 之类的不再赘述。
第一种:spring封装的线程池
- 首先定义配置类,这个配置类需要实现AsyncConfiguer接口,并实现它的方法
- 异步线程的执行者,在里面配置自动执行的东西,比如线程池参数
- 线程异常处理
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
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;
import java.util.concurrent.ThreadPoolExecutor;
/**
* Created with IntelliJ IDEA.
* http://ichenqiang.com
*
* @author iChenQiang
* @version 1.0
* @Date: 2019/7/16 14:18
* @Description:
*/
@Configuration
@EnableAsync
public class ExecutorConfig implements AsyncConfigurer {
private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);
/**
* TODO: 此方法名称为asyncPromiseExecutor,即在spring中注入了一个名字为asyncPromiseExecutor的bean
* 方法名只要在项目中唯一性,可以适当任意取(最好遵循一定的规则)
* 使用方法:在需要加入线程池的方法上增加注解@Async("asyncPromiseExecutor")就可以加入此线程池异步执行
*/
@Bean
public Executor asyncPromiseExecutor() {
logger.info("Starting AsyncPromiseExecutor!");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心线程数
executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
//最大线程数量
executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 5);
//线程池的队列容量
executor.setQueueCapacity(Runtime.getRuntime().availableProcessors() * 5);
// executor.setCorePoolSize(5);
// executor.setMaxPoolSize(20);
// executor.setQueueCapacity(30);
executor.setThreadNamePrefix("fastcloud-kingdm-");
/**
* rejection-policy:当pool已经达到max size的时候,如何处理新任务
* CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
*/
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//初始化执行器
executor.initialize();
return executor;
}
/*异步任务中异常处理*/
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}
- 创建线程任务执行类
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class TreadTasks {
@Async
public void startMyTreadTask() {
System.out.println("this is my async task");
}
}
- 调用异步线程任务
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import ds.watsons.app.label.service.TreadTasks;
@Controller
public class AsyncTaskUse {
@Autowired
private TreadTasks treadTasks;
@GetMapping("/startMysync")
public void useMySyncTask() {
treadTasks.startMyTreadTask();
}
}
第二种:异步处理最简单的代码
public void test(){
new Thread(()->doReplace(replaceLog)).start();
}
public void doReplace(String replaceLog){
//异步处理的业务
}