多线程 线程组 ThreadGroup

时间:2024-10-10 08:35:26
 package org.zln.thread;

 import java.util.Date;

 /**
* Created by sherry on 000024/6/24 22:30.
*/
public class TestThreadGroup {
public static void main(String[] args) throws InterruptedException {
ThreadGroup group1 = new ThreadGroup("group1");
/*group2从属于group1 group1是父 group2是子*/
ThreadGroup group2 = new ThreadGroup(group1,"group2");
/*关联线程与线程组*/
Thread t1 = new Thread(group1,new TestThread(1000,"AAA"));
Thread t2 = new Thread(group2,new TestThread(1000,"BBB"));
Thread t3 = new Thread(group2,new TestThread(1000,"CCC"));
t1.start();
t2.start();
t3.start();
System.out.println("线程组1线程数量:"+group1.activeCount());
System.out.println("线程组2线程数量:"+group2.activeCount());
System.out.println("线程组1线程组数量:"+group1.activeGroupCount()); /*10秒后停止所有任务*/
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
System.out.println(new Date());
}
group1.stop();//这里只是为了演示 stop是不安全的。实际开发中不要用
}
}

 package org.zln.thread;

 import java.util.Date;

 /**
* Created by coolkid on 2015/6/21 0021.
*/
public class TestThread extends Thread{
private int time;//休眠时间
private String user;//调用用户 public TestThread(int time, String user) {
this.time = time;
this.user = user;
} @Override
public void run() {
while (true){
try {
System.out.println(Thread.currentThread().getName()+"\t"+user+" 休息 "+time+"ms-"+new Date());
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} public static void main(String[] args) {
Thread thread1 = new TestThread(1000,"Jack");
Thread thread2 = new TestThread(3000,"Mike");
thread2.setPriority(Thread.MAX_PRIORITY);
thread1.start();
thread2.start();
}
}

使用线程组的好处在于能够对线程组内的线程进行批量操作,同时线程组之间也可以拥有包含关系,或者叫父子关系