多线程之ThreadGroup

在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;
	
	@Override
	public 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());
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值