/**
* <p>Title: 線程組群</p>
* <p>Description: 通過線程組管理下面的多個線程。</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: myThreadgroup.java</p>
* @version 1.0
*/
public class myThreadgroup extends Thread {
public static int flag=1;
ThreadGroup tgA;
ThreadGroup tgB;
/**
*<br>方法說明:主方法
*<br>輸入參數:
*<br>返回類型:
*/
public static void main(String[] args){
myThreadgroup dt = new myThreadgroup();
//聲明線程組A
dt.tgA = new ThreadGroup("A");
//聲明線程組B
dt.tgB = new ThreadGroup("B");
for(int i=1;i<3;i++)
new thread1(dt.tgA,i*1000,"one"+i);
for(int i=1;i<3;i++)
new thread1(dt.tgB,1000,"two"+i);
//啟動本線程和所有線程組
dt.start();
}
/**
*<br>方法說明:覆蓋run方法,控制線程組
*<br>輸入參數:
*<br>返回類型:
*/
public void run(){
try{
this.sleep(5000);
this.tgB.checkAccess();
//停止線程組B,
this.tgB.stop();
System.out.println("**************tgB stop!***********************");
this.sleep(1000);
//檢查線程組A是否可以更改
this.tgA.checkAccess();
//停止線程組A
this.tgA.stop();
System.out.println("**************tgA stop!***********************");
}catch(SecurityException es){
System.out.println("**"+es);
}catch(Exception e){
System.out.println("::"+e);
}
}
}
/**
* <p>Title: 線程類</p>
* <p>Description: 通過構造器的參數,實現不同的線程</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: thread1.java</p>
* @author 杜江
* @version 1.0
*/
class thread1 extends Thread {
int pauseTime;
String name;
public thread1(ThreadGroup g,int x, String n) {
super(g,n);
pauseTime = x;
name = n;
start();
}
/**
*<br>方法說明:必須覆蓋的方法。
*<br>輸入參數:
*<br>返回類型:
*/
public void run ()
{
while(true) {
try {
System.out.print(name+"::::");
this.getThreadGroup().list();//獲取線程組信息
Thread.sleep(pauseTime);
} catch(Exception e) {
System.out.println(e);
}
}
}
}