首页 > 编程语言 > 详细

java 自定义线程池

时间:2021-08-03 22:46:34      阅读:27      评论:0      收藏:0      [点我收藏+]
import lombok.Getter;

import javax.annotation.PostConstruct;
import java.util.concurrent.*;
//创建一个线城池
public class LogOptionThreadPool {
private static final ThreadFactory mThreadFactory = new ThreadFactory() {
//线程的名字
public Thread newThread(Runnable r) {
return new Thread(r,"OperationLogThread");
}
};
BlockingQueue<Runnable> workQueue=new LinkedBlockingDeque<>(1000);

@Getter
ThreadPoolExecutor logThread;

@PostConstruct
public void init(){
logThread=new ThreadPoolExecutor(2,2,60, TimeUnit.SECONDS,workQueue,
mThreadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
logThread.prestartAllCoreThreads();
}
}

//在service中注入该线程,调用execute方法,开启线程,线程里面放入参数
@Service
@RequiredArgsConstructor
public class LogOptionalService {
// 异步保存操作记录
private final LogOptionThreadPool logOptionThreadPool;

public void doLog(T t){
     //参数目前都是随便写的
logOptionThreadPool.getLogThread().execute(new OptionRun(t));
}
}

在实现类中,继承 Runnable 接口,然后在run方法里面实现具体的逻辑
public class OptionRun implements Runnable{
private Integer teamId;
private String operationName;
private String operation;

public OptionRun(Integer teamId, String operationName, String operation) {
this.teamId = teamId;
this.operationName = operationName;
this.operation = operation;
}

public void run() {
//处理逻辑
//insert(teamId,operationName,operation);
}
}



java 自定义线程池

原文:https://www.cnblogs.com/foreverstudy/p/15095867.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!