Java高并发编程学习--14. 线程的ThreadGroup的基本操作

一、ThreadGroup的基本操作

package p106_thread_group;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName ThreadGroupBasicOption
 * @Description TODO
 * ThreadGroup的基本操作
 * 1. activeCount()用于获取group中活跃的线程,这只是个估计值,并不能百分之百地
 * 保证数字一定正确,原因前面已经分析过,该方法会递归获取其他子group中的活
 * 跃线程。
 * 2. activeGroupCount()用于获取group中活跃的子group,这也是一个近似估值,该方
 * 法也会递归获取所有的子group,
 * 3. getMaxPnority()用于获取group的优先级,默认情况下,Group的优先级为10,在
 * 该group中,所有线程的优先级都不能大于group的优先级。
 * 4. getName()用于获取group的名字。
 * 5. getparent()用于获取group的父group,如果父group不存在,则会返回nu出比如
 * systemgroup的父group就为null
 * 6. list()该方法没有返回值,执行该方法会将group中所有的活跃线程信息全部输出到
 * 控制台,也就是System.out
 * 7. parentOf(ThreadGroupg)会判断当前group是不是给定group的父group,另外如
 * 果给定的group就是自己本身,那么该方法也会返回true
 * 8. setMaxPrionty(intpn)会指定group的最大优先级,最大优先级不能超过父group
 * 的最大优先级,执行该方法不仅会改变当前group的最大优先级,还会改变所有子
 * group的最大优先级。
 * @Author Cays
 * @Date 2019/5/4 8:44
 * @Version 1.0
 **/
public class ThreadGroupBasicOption {
    public static void main(String[] args) throws InterruptedException {
        //创建ThreadGroup和Thread
        ThreadGroup group1 = new ThreadGroup("group1");
        Thread thread = new Thread(group1,()->{
            while (true){
                try {
                    TimeUnit.SECONDS.sleep(1);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        },"thread");
        thread.setDaemon(true);
        thread.start();
        TimeUnit.MILLISECONDS.sleep(2);
        //thead group的基本操作
        ThreadGroup mainGroup = Thread.currentThread().getThreadGroup();
        System.out.println("activeCount = "+mainGroup.activeCount());
        System.out.println("activeGroupCount = "+mainGroup.activeGroupCount());
        System.out.println("getMaxPriority = "+mainGroup.getMaxPriority());
        System.out.println("getParent = "+mainGroup.getParent());
        mainGroup.list();
        System.out.println("===============================================");
        System.out.println("parentOf = "+mainGroup.parentOf(mainGroup));
        System.out.println("parentof = "+mainGroup.parentOf(group1));
        //优先级
        System.out.println("group1.getMaxPriority = "+group1.getMaxPriority());
        System.out.println("thread.getPriority = "+thread.getPriority());
        //改变group1的最大的优先级
        group1.setMaxPriority(3);
        System.out.println("group1.getMaxPriority = "+group1.getMaxPriority());
        System.out.println("thread.getPriority = "+thread.getPriority());
        /**
         * 虽然出现thread的优先级大于group1的情况,但之后加入group1的thread不会大于
         * group1的最大优先级
         */
    }
}

二、结果

Java高并发编程学习--14. 线程的ThreadGroup的基本操作