1,这是线程池管理工具类,在系统关闭时确保任务执行完毕,自定义线程名字,自定义抛弃策略默认使用了CallerRunsPolicy拒绝策略
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.TimeUnit;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** @author yannan * 20231128*/public class ThreadUtil {private static final Logger logger = LoggerFactory.getLogger(ThreadUtil.class);public static class CustomThreadFactory implements ThreadFactory {private final String namePrefix;public CustomThreadFactory(String namePrefix) {this.namePrefix = namePrefix;}public Thread newThread(Runnable runnable) {Thread thread = new Thread(runnable);thread.setName(namePrefix + thread.getId());return thread;}}/*** 轮询等待ExecutorService线程池中所有线程执行完毕* * @param executorService*/public static void isTerminated(ExecutorService executorService) {StringBuffer sb = new StringBuffer();executorService.submit(() -> {sb.append(Thread.currentThread().getName());// System.out.println("Task executed by thread: " + threadName);});executorService.shutdown();// 轮询等待ExecutorService线程池中所有线程执行完毕while (true) {if (executorService.isTerminated()) {// System.err.println(executorService.getClass().getName()+" end");logger.info("线程池 " + sb.toString() + " END 关闭成功");break;}try {Thread.sleep(10);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}/*** 等待超时* * @param executorService*/public static void awaitTermination(ExecutorService executorService) {try {executorService.awaitTermination(5 * 60, TimeUnit.SECONDS);} catch (InterruptedException e) {e.printStackTrace();logger.info("等待超时,直接关闭");}}/*** */public static ExecutorService newSingleThreadExecutor(String threadName) {// "Log-Thread-"ThreadFactory threadFactory = new ThreadUtil.CustomThreadFactory(threadName);ExecutorService executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(), threadFactory, callerRunsPolicy());return executorService;}public static ExecutorService newFixedThreadPool(int nThreads, String threadName) {ThreadFactory threadFactory = new ThreadUtil.CustomThreadFactory(threadName);ExecutorService executorService = new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(), threadFactory, callerRunsPolicy());return executorService;}/*** CallerRunsPolicy拒绝策略,相对而言它就比较完善了,当有新任务提交后,如果线程池没被关闭且没有能力执行,则把这个任务交于提交任务的线程执行,也就是谁提交任务,谁就负责执行任务。这样做主要有两点好处。* @return*/public static CallerRunsPolicy callerRunsPolicy() {return new ThreadPoolExecutor.CallerRunsPolicy();}public static int getCorePoolSize(ExecutorService executorService) {int threadSize = 0;if (executorService instanceof ThreadPoolExecutor) {threadSize = ((ThreadPoolExecutor) executorService).getCorePoolSize();logger.info("核心线程数量为:" + threadSize);}return threadSize;}
}