当我们需要对一类线程做相同的操作时,不妨将这些线程当成集合来处理
java为我们提供了线程组ThreadGroup类,13503079814

构造方法

1
2
public ThreadGroup(String name);//构建一个新线程组,并为该线程组设置名称
public ThreadGroup(ThreadGroup parent, String name)//构建一个先线程组,并传入父线程组

获取

1
2
3
4
public final String getName()//获取线程组名称
public final ThreadGroup getParent()//获取当前线程组的父线程组
//返回此线程组的最高优先级。作为此线程组一部分的线程不能拥有比最高优先级更高的优先级。
public final int getMaxPriority()
简单的测试案例 :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
ThreadGroup fatherGroup = new ThreadGroup("父线程组");
ThreadGroup childrenGroup = new ThreadGroup(fatherGroup,"子线程组");
Thread thread1 = new Thread("线程1");
Thread thread2 = new Thread(fatherGroup,"线程2");
Thread thread3 = new Thread(childrenGroup,"线程3");
System.out.println("main所在线程组 : "+Thread.currentThread().getThreadGroup().getName());
System.out.println("thread1所在线程组 : "+thread1.getThreadGroup().getName());
System.out.println("thread2所在线程组 : "+thread2.getThreadGroup().getName());
System.out.println("thread3所在线程组 : "+thread3.getThreadGroup().getName());
System.out.println("thread3所在线程组的父线程组 : "
+thread3.getThreadGroup().getParent().getName());
thread2.setPriority(8);
System.out.println("main线程组优先级 : "+Thread.currentThread().getThreadGroup().getMaxPriority());
System.out.println("父线程组默认优先级 : "+fatherGroup.getMaxPriority());
System.out.println("子线程组默认优先级 : "+childrenGroup.getMaxPriority());
fatherGroup.setMaxPriority(3);
System.out.println("父线程组修改优先级 : "+fatherGroup.getMaxPriority());
System.out.println("父线程组被修改后优先级 : "+childrenGroup.getMaxPriority());
Thread thread5 = new Thread(childrenGroup,"线程5");
System.out.println(thread2.getName()+" : "+thread2.getPriority());
System.out.println(thread3.getName()+" : "+thread3.getPriority());
System.out.println(thread5.getName()+" : "+thread5.getPriority());
执行代码可以得到结论
    main线程以及新建线程的默认线程组是main线程组
    线程组的优先级默认为10
    修改父线程组的最大优先级,子线程组也随之修改
    修改线程组最大优先级不影响内部线程的优先级
    线程优先级不可超过其线程组,若超过则设置为线程组最大优先级
        当然超过优先级访问依然抛异常
    创建线程的时候,它的优先级<=它的线程组最大优先级
执行结果如下 :