最近异步消息处理的项目用到了ThreadGroup 把thread放到了threadGroup中,于是对threadGroup的作用和意义有了进一步的探究与好奇。
private static final ExecutorService EXECUTOR_SERVICE = new ThreadPoolExecutor(16, 32, 5L, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1000), new ThreadFactory() { private final ThreadGroup threadGroup = new ThreadGroup("fileTemplateMethodThreadGroup"); private final AtomicInteger threadNumber = new AtomicInteger(1); @Override public Thread newThread(Runnable r) { return new Thread(threadGroup, r, "fileTemplateMethod-thread-pool-" + threadNumber.getAndIncrement()); } }, (r, executor) -> { if (!executor.isShutdown()) { /* 丢弃队列最老的数据 */ if (executor.getQueue().poll() != null) { Cat.logMetricForCount(CatConstant.METRIC_DISCARD_FILE_TASK_COUNT); } executor.execute(r); } });
ThreadGroup 可以把thread的名字统一起来。一起处理catch。
ThreadGroup是Java提供的一种对线程进行分组管理的手段,可以对所有线程以组为单位进行操作,如设置优先级、守护线程等。
线程组也有父子的概念,如下图:
ThreadGroup是位于java.lang包下的一个类,用于统一的线程管理.一旦一个线程加入到一个线程组后,就不能更换线程所在的线程组
将当前线程加入到线程组中。
public class ThreadGroupCreator { public static void main(String[] args) { //获取当前线程的group ThreadGroup currentGroup = Thread.currentThread().getThreadGroup(); //在当前线程执行流中新建一个Group1 ThreadGroup group1 = new ThreadGroup("Group1"); //Group1的父线程,就是main线程所在Group System.out.println(group1.getParent() == currentGroup); //定义Group2, 指定group1为其父线程 ThreadGroup group2 = new ThreadGroup(group1, "Group2"); System.out.println(group2.getParent() == group1); } }
将ThreadGroup中活跃的线程引用复制到线程组
Thread[] threads = new Thread[num]; threadGroup.enumerate(threads); for (Thread t : threads) { System.out.println("线程名-" + t.getName()); }
线程组的基本操作
注意:后添加进线程组的线程,其优先级不能大于线程组的优先级
public class ThreadGroupBasic { public static void main(String[] args) throws InterruptedException { ThreadGroup group = new ThreadGroup("group1"); Thread thread = new Thread(group, () -> { while(true) { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } }, "thread"); thread.setDaemon(true); thread.start(); TimeUnit.MILLISECONDS.sleep(1); ThreadGroup mainGroup = Thread.currentThread().getThreadGroup(); //递归获取mainGroup中活跃线程的估计值 System.out.println("activeCount = " + mainGroup.activeCount()); //递归获mainGroup中的活跃子group System.out.println("activeGroupCount = " + mainGroup.activeGroupCount()); //获取group的优先级, 默认为10 System.out.println("getMaxPriority = " + mainGroup.getMaxPriority()); //获取group的名字 System.out.println("getName = " + mainGroup.getName()); //获取group的父group, 如不存在则返回null System.out.println("getParent = " + mainGroup.getParent()); //活跃线程信息全部输出到控制台 mainGroup.list(); System.out.println("----------------------------"); //判断当前group是不是给定group的父线程, 如果两者一样,也会返回true System.out.println("parentOf = " + mainGroup.parentOf(group)); System.out.println("parentOf = " + mainGroup.parentOf(mainGroup)); } }
原文链接:https://www.cnblogs.com/aspirant/p/10644180.html