Demo20 :通過線程組管理多線程(通過構造器的參數實現不同的線程)

package demo20;

/**
 * <p>Title: 線程組羣</p>
 * <p>Description: 通過線程組管理下面的多個線程。</p>
 */
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>
 */
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);
      }
    }
   }
}

運行結果:
這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章