熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java高級技術 >> 正文

Java-多線程組的控制

2013-11-23 19:48:55  來源: Java高級技術 

  class NewThread extends Thread{

  boolean suspendFlag;

  NewThread(String threadname ThreadGroup tgOb){

  super(tgOb threadname);

  Systemoutprintln(New thread: +this);

  suspendFlag = false;

  start();

  }

  public void run(){

  try{

  for(int i=;i>;i){

  Systemoutprintln(getName()+: +i);

  Threadsleep();

  synchronized(this){

  while(suspendFlag){

  wait();

  }

  }

  }

  }catch(Exception e){

  Systemoutprintln(Exception in +getName());

  }

  Systemoutprintln(getName()+exiting);

  }

  void mysuspend(){

  suspendFlag = true;

  }

  synchronized void myresume(){

  suspendFlag = false;

  notify();

  }

  }

  public class test {

  public static void main(String[] args) {

  // TODO Autogenerated method stub

  ThreadGroup groupA = new ThreadGroup(Group A);

  ThreadGroup groupB = new ThreadGroup(Group B);

  NewThread ob = new NewThread(one groupA);

  NewThread ob = new NewThread(Tow groupA);

  NewThread ob = new NewThread(three groupB);

  NewThread ob = new NewThread(Four groupB);

  Systemoutprintln(Suspending Group A);

  Thread tga[] = new Thread[groupAactiveCount()];

  groupAenumerate(tga);

  for(int i=;i<tgalength;i++){

  ((NewThread)tga[i])mysuspend();

  }

  try {

  Threadsleep();

  }catch(InterruptedException e){

  Systemoutprintln(Main thread interrupted);

  }

  Systemoutprintln(Resuming Group A);

  for(int i=;i<tgalength;i++){

  ((NewThread)tga[i])myresume();

  }

  try {

  Systemoutprintln(Waiting for threads to finish);

  objoin();

  objoin();

  objoin();

  objoin();

  }catch (Exception e){

  Systemoutprintln(Exception in Main thread);

  }

  Systemoutprintln(Main thread exiting);

  }

  }


From:http://tw.wingwit.com/Article/program/Java/gj/201311/27490.html
  • 上一篇文章:

  • 下一篇文章:
  • Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.