ThreadGroup类是线程组,表示一组线程的集合,可用其对一批线程和线程组进行管理。可把线程归属到指定的线程组中,线程组中可以有线程对象,也可以有线程组,组中还可以有线程,这样的组织结构类似于树形结构。
开发人员创建的所有线程,都属于指定线程组;若没显式指定属于哪个线程组,则该线程就属于默认线程组,即main线程组。缺省情况下,子线程和父线程处于同一个线程组。
说明:创建线程时,可指定其归属的线程组;线程运行中,不能改变它的归属线程组;即线程一旦指定所在的线程组就不可改变。
2、线程组作用1)安全
同一个线程组的线程,可以相互修改彼此的数据。
同一个线程组的线程,不可以相互修改彼此的数据。
如此,在一定程度上保证数据安全。
2)管理
可以实现对线程以及线程组对象的批量管理;对线程或线程组对象进行有效的组织与控制。
3、线程组使用示例1.线程关联线程组:一级关联
一级关联,是指父对象中有子对象,但并不创建孙对象。举例:创建一个线程组,然后将创建的线程归属到该组中,从而对这些线程进行有效的管理。
2.线程关联线程组:多级关联
多级关联,是指父对象中有子对象,子对象中再创建孙对象也就出现了子孙的效果了。举例:将子线程组归属到某个线程组,再将创建的线程归属到子线程组。
package threads;
public class ThreadGroupTest implements Runnable {
@Override
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
Thread currentThread = Thread.currentThread();
System.out.println("currentThread:" + currentThread.getName()
+ "; threadGroup:" + currentThread.getThreadGroup().getName()
+ "; parentThreadGroup:" + currentThread.getThreadGroup().getParent().getName());
Thread.sleep(2000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ThreadGroup rootGroup = new ThreadGroup("线程组root");
Thread thread0 = new Thread(rootGroup, new ThreadGroupTest(), "thread-0");
thread0.start();
ThreadGroup group1 = new ThreadGroup(rootGroup, "线程组1");
ThreadGroup group2 = new ThreadGroup(rootGroup, "线程组2");
Thread thread1 = new Thread(group1, new ThreadGroupTest(), "thread-1");
Thread thread2 = new Thread(group1, new ThreadGroupTest(), "thread-2");
thread1.start();
thread2.start();
Thread thread3 = new Thread(group2, new ThreadGroupTest(), "thread-3");
Thread thread4 = new Thread(group2, new ThreadGroupTest(), "thread-4");
thread3.start();
thread4.start();
}
}



