小公司偶尔有一些需要用到线程的地方自用的方法
不确定好不好,但是暂时没出啥大问题
因为没有高并发的处理经验,所以且发出来看看有无路过大佬指点一下
serviceImpl实现类中定义内部类
// 类内部定义线程池
private static final ThreadPoolExecutor THREAD_POOL;
static {
int corePoolSize = Math.max(2, Runtime.getRuntime().availableProcessors() * 2);
THREAD_POOL = new ThreadPoolExecutor(
corePoolSize,
corePoolSize,
60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(100),
(r, executor) -> {
// 拒绝策略:由调用线程自己执行
r.run();
}
);
}
创建线程类
public class DemoThread implements Runnable{
DemoService demoService;
Long demoId;
public DemoThread( DemoService demoService,
Long demoId) {
this.demoService = demoService;
this.demoId = demoId;
}
@Override
public void run() {
try{
demoService.toRunFun(demoId);
}catch (RuntimeException r){
//记录日志
}
}
}
启动调用线程
@Autowired
DemoService demoService;
private void demoFunction(Long demoId) {
...
THREAD_POOL.submit(new DemoThread(demoService,demoId));
...
}
简单的一个线程池调用就完成了
线程使用的方法和参数需要通过构造方法传入到线程内部

被折叠的 条评论
为什么被折叠?



