线程组的创建
什么是线程组
Java线程组的出现,是为了方便用户在多线程的情况下对线程进行分组管理。线程组,即线程的分组,它表示一组线程的集合。线程组中包含一个到多个线程,甚至可以包含一个到多个线程组,及它的的组织形式是树状的。如下图所示,后面的代码也会如下图所示创建一个具有树状形式的线程组
线程组的创建
// 1.创建一个 SayHiThread 线程类
public class SayHiThjread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+": Hi~~!, "+"我在["+
Thread.currentThread().getThreadGroup().getName()+"]"+
"线程组哟,我的父级线程组是:"+Thread.currentThread().getThreadGroup().getParent().getName());
}
}
// 2. 实例化4个线程对象,并创建一个线程组threadGroup01
public class CreateThreadGroup {
public static void main(String[] args) {
ThreadGroup threadGroup01 = new ThreadGroup("ThreadGroup-01");
Thread thread01 = new Thread(new SayHiThjread());
thread01.setName("Thread-01");
Thread thread02 = new Thread(new SayHiThjread());
thread02.setName("Thread-02");
// 将 thread03 和 thread04 放入 threadGroup01 线程组中
Thread thread03 = new Thread(threadGroup01,new SayHiThjread(),"Thred-03");
Thread thread04 = new Thread(threadGroup01,new SayHiThjread(),"Thread-04");
System.out.println(Thread.currentThread().getName()+": Hi~~!, "+
"我在["+Thread.currentThread().getThreadGroup().getName()+"]"+"线程," +
"我的父级线程是:"+Thread.currentThread().getThreadGroup().getParent().getName());
thread01.start();
thread02.start();
thread03.start();
thread04.start();
//获得当前的main线程组,并且遍历出该线程组下的所有线程
ThreadGroup mainGroup = Thread.currentThread().getThreadGroup();
Thread[] tmpThreadList = new Thread[10];
mainGroup.enumerate(tmpThreadList);
int i = 0;
for(Thread tmpThread : tmpThreadList){
if(tmpThread==null){
continue;
}
System.out.println("main线程组中运行的线程有:("+i+")"+tmpThread.getName());
i++;
}
//获得ThreadGroup01线程组,并且遍历出该线程组下的所有线程
tmpThreadList = new Thread[10];
threadGroup01.enumerate(tmpThreadList);
for(Thread tmpThread : tmpThreadList){
if(tmpThread==null){
continue;
}
System.out.println("ThreadGroup-01线程组中运行的线程有:("+i+")"+tmpThread.getName());
i++;
}
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadGroup01.getName()+"Hi ~~!,"+
"我是一个线程组,我属于线程组["+
threadGroup01.getParent().getName() );
}
}
// 3.输出结果
main: Hi~~!, 我在[main]线程,我的父级线程是:system
main线程组中运行的线程有:(0)main
main线程组中运行的线程有:(1)Monitor Ctrl-Break
main线程组中运行的线程有:(2)Thread-01
main线程组中运行的线程有:(3)Thread-02
main线程组中运行的线程有:(4)Thred-03
main线程组中运行的线程有:(5)Thread-04
ThreadGroup-01线程组中运行的线程有:(6)Thred-03
ThreadGroup-01线程组中运行的线程有:(7)Thread-04
Thread-01: Hi~~!, 我在[main]线程组哟,我的父级线程组是:system
Thread-02: Hi~~!, 我在[main]线程组哟,我的父级线程组是:system
Thred-03: Hi~~!, 我在[ThreadGroup-01]线程组哟,我的父级线程组是:main
Thread-04: Hi~~!, 我在[ThreadGroup-01]线程组哟,我的父级线程组是:main
ThreadGroup-01Hi ~~!,我是一个线程组,我属于线程组[main
Process finished with exit code 0