java 自定义线程池

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);
}
}



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