线程组使用

来源:互联网 发布:mysql数据库登陆 编辑:程序博客网 时间:2024/06/01 09:58

线程组

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

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



示例

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

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()







原创粉丝点击