线程组使用

线程组

可以把线程归属到某一个线程组中,线程组中可以有线程对象,也可以有线程对象,组中可以有线程,这样线程组可以类似树形。

线程组的使用主要是方便线程的管理维护操作:



示例

(通过线程组的方式组织多个线程并且批量停止所有线程

1、创建线程A和B

public class ThreadA extends Thread {
	// 设置新的构造函数,传入线程组对象
	public ThreadA(ThreadGroup group, String name) {
		super(group, name);
	}

	public void run() {
		while (true) {
			System.out.println("threadA...");
			// 根据停止标记停止
			if (this.isInterrupted()) {
				System.out.println("当前线程:" + this.getName() + "停止了!");
				break;
			}
		}
	}
}

public class ThreadB extends Thread {

	public ThreadB(ThreadGroup group, String name) {
		super(group, name);
		// TODO Auto-generated constructor stub
	}

	public void run() {
		while (true) {
			System.out.println("threadB...");
			// 根据停止标记停止
			if (this.isInterrupted()) {
				System.out.println("当前线程:" + this.getName() + "停止了!");
				break;
			}
		}
	}
}

2、具体测试Client

public class Client {

	public static void main(String[] args) {
		try {
			// 创建线程组
			ThreadGroup group = new ThreadGroup("自定义线程组");
			ThreadA threadA = new ThreadA(group, "threadA");
			ThreadB threadB = new ThreadB(group, "threadB");
			// 开启
			threadA.start();
			threadB.start();
			Thread.sleep(1000);
			// 输出线程组信息
			System.out.println("current thread size :" + group.activeCount());
			System.out.println("current thread group name :" + group.getName());

			// 停止线程组内所有线程
			System.out.println("current thread group stop start...");
			group.interrupt();
			System.out.println("current thread group stop end!");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


以上代码通过线程组组织了多个线程,并且可以使用线程组的interrupt()方法停止所包含的多个线程。

运行之后输出:

...

threadB...
threadB...
current thread size :2
current thread group name :自定义线程组
current thread group stop start...
threadB...
threadA...
current thread group stop end!
当前线程:threadA停止了!
当前线程:threadB停止了!


备注:

在实例化各个线程的时候,如果不指定所属的线程组,则这些线程自动归到当前线程对象所属的线程组中,也就是说隐似的在一个线程组中添加了子线程。比如:在main方法中创建多个线程,如果不明确的设置所属线程组的话,则这些线程默认都属于main所在的线程组。
其中main方法所在的线程组即是main,main线程的父级线程组即是jvm线程组system,可以在main中通过以下获取:

Thread.currentThread().getThreadGroup().getName();
Thread.currentThread().getThreadGroup().getParent().getName()







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值