java线程池管理工具类

24 篇文章 0 订阅
3 篇文章 0 订阅

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 block
				e.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;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值