线程池
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 线程池工具类,工程所有多线程均调用此类,控制整个工程允许的最大线程数
*/
@Slf4j
public class ThreadPool {
public static ThreadPool threadPool;
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(30,
new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
public static ThreadPool getInstance() {
if (threadPool == null) {
threadPool = new ThreadPool();
}
return threadPool;
}
public void run(Runnable r) {
executorService.execute(r);
}
public void run(Runnable r, long initialDelay, long period, TimeUnit unit) {
executorService.scheduleAtFixedRate(r, initialDelay, period, unit);
}
}
使用方式:
在需要使用的地方添加
ThreadPool.getInstance().run(() -> {
System.out.println("使用线程池打印");
});