标签:
1 package org.zln.thread; 2 3 import java.util.Date; 4 5 /** 6 * Created by sherry on 000024/6/24 22:30. 7 */ 8 public class TestThreadGroup { 9 public static void main(String[] args) throws InterruptedException { 10 ThreadGroup group1 = new ThreadGroup("group1"); 11 /*group2从属于group1 group1是父 group2是子*/ 12 ThreadGroup group2 = new ThreadGroup(group1,"group2"); 13 /*关联线程与线程组*/ 14 Thread t1 = new Thread(group1,new TestThread(1000,"AAA")); 15 Thread t2 = new Thread(group2,new TestThread(1000,"BBB")); 16 Thread t3 = new Thread(group2,new TestThread(1000,"CCC")); 17 t1.start(); 18 t2.start(); 19 t3.start(); 20 System.out.println("线程组1线程数量:"+group1.activeCount()); 21 System.out.println("线程组2线程数量:"+group2.activeCount()); 22 System.out.println("线程组1线程组数量:"+group1.activeGroupCount()); 23 24 /*10秒后停止所有任务*/ 25 for (int i = 0; i < 10; i++) { 26 Thread.sleep(1000); 27 System.out.println(new Date()); 28 } 29 group1.stop();//这里只是为了演示 stop是不安全的。实际开发中不要用 30 } 31 }
1 package org.zln.thread; 2 3 import java.util.Date; 4 5 /** 6 * Created by coolkid on 2015/6/21 0021. 7 */ 8 public class TestThread extends Thread{ 9 private int time;//休眠时间 10 private String user;//调用用户 11 12 public TestThread(int time, String user) { 13 this.time = time; 14 this.user = user; 15 } 16 17 @Override 18 public void run() { 19 while (true){ 20 try { 21 System.out.println(Thread.currentThread().getName()+"\t"+user+" 休息 "+time+"ms-"+new Date()); 22 Thread.sleep(time); 23 } catch (InterruptedException e) { 24 e.printStackTrace(); 25 } 26 } 27 } 28 29 public static void main(String[] args) { 30 Thread thread1 = new TestThread(1000,"Jack"); 31 Thread thread2 = new TestThread(3000,"Mike"); 32 thread2.setPriority(Thread.MAX_PRIORITY); 33 thread1.start(); 34 thread2.start(); 35 } 36 }
使用线程组的好处在于能够对线程组内的线程进行批量操作,同时线程组之间也可以拥有包含关系,或者叫父子关系
标签:
原文地址:http://www.cnblogs.com/sherrykid/p/4598857.html