[JAVA100例]063、線程群組

來源:互聯網
上載者:User

/**
* <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);
   }
  }
  }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.