多线程之ThreadGroup

来源:互联网 发布:复杂网络系统与动力学 编辑:程序博客网 时间:2024/05/25 08:13

在Java中每一个线程都归属于某一个线程组(ThreadGroup)管理,即线程组表示一个线程的集合。此外,线程组也可以包含其他的线程组。线程组可以设定所有线程的一些

属性。通过Thread.currentThread().getThreadGroup().getName()可以获取当前线程所属于的线程组。

ThreadGroup方法介绍

1. 构造方法:创建一个指定名称的线程组,默认该线程组的父线程组为当前线程的父线程组

public ThreadGroup(String name)

2.  构造方法: 创建一个指定名称和父线程组的线程组

public ThreadGroup(ThreadGroup parent, String name)

3.  获取线程组活动线程的数量

public int activeCount() 

4.  获取线程组活动线程组的数量

public int activeGroupCount() 

5.  获取线程组的名称
public final String getName() 

6.  获取线程组的父线程组

public final ThreadGroup getParent()


下面是一个简单的demo

public class PrintTask implements Runnable{private volatile static int count = 0;@Overridepublic void run(){while(true){try {Thread.sleep(1*1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName()+":"+ ++count);}}}

public class MainThread {public static void main(String[] args) {ThreadGroup group = new ThreadGroup("print-msg-group");Thread thread1 = new Thread(group, new PrintTask(), "thread-1");Thread thread2 = new Thread(group, new PrintTask(), "thread-2");Thread thread3 = new Thread(group, new PrintTask(), "thread-3");thread1.start();thread2.start();thread3.start();System.out.println(group.activeCount());}}



0 0
原创粉丝点击