之前遇到一个线程的写法,可以把service的方法直接通过线程池异步执行。
只记得大概的写法了
//一个普通的service
public class Aservice {
public class b() {
.....
}
}
//这是一个线程池工具类,具体的代码忘记了,跪求大佬指点迷津
public class ExecutorUtil {
private final static Executor EXECUTOR = new ThreadPoolExecutor(8, 16, 5000, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(10), new ThreadPoolExecutor.CallerRunsPolicy());
public static void async(...) {
...
}
}
//使用方法大概是这样的,这样就可以直接把b方法异步执行
ExecutorUtil.EXECUTOR.async(()->b);
private ExecutorService worker = new ThreadPoolExecutor(1, 10,
60, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(2*60));
// 异步
worker.execute(()->{
try {
Aservice.b();
} catch (Exception e) {
log.error("async failed :{}", e);
}
});
既然你说是springboot 那么还有注解方式异步
@Async
//线程池执行器
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
5,
10,
10,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue(3),
new ThreadPoolExecutor.AbortPolicy());
threadPoolExecutor.execute(thread1);
好像是spring boot线程池???
1、Spring boot启动类上添加注解@EnableAsync,开始异步执行
2、在配置类中将异步执行的线程池放到bean工厂,配置类即被@Configuration修饰的类,线程池定义如下
@Bean("customThreadPool")
public ExecutorService generateCalchasThreadPool() {
return Executors.newCachedThreadPool();
}
3、Service中的方法上加@Async注解,并且要加上异步执行使用的线程池,例如:("customThreadPool")
java 创建线程的三种方式、创建线程池的四种方式_smileTimLi的博客-CSDN博客_创建线程池的几种方式
供参考