//程序会停在join那里不动,这是为什么啊?(好像是哪个线程不能结束?这是为什么啊!)
public class ThreadGroupDemo
{public static void main(String args[])
{
ThreadGroup groupA=new ThreadGroup("groupA");
ThreadGroup groupB=new ThreadGroup("groupB");newThread ob1=new newThread("one",groupA);
newThread ob2=new newThread("Two",groupA);
newThread ob3=new newThread("Three",groupB);
newThread ob4=new newThread("Four",groupB);System.out.println("\nHere is output from list():");
groupA.list();//LIST显示关于线程组的信息
groupB.list();
System.out.println();System.out.println("Suspending Group A");
Thread tga[]=new Thread[groupA.activeCount()];//activeCount返回线程组加上以这个线程作为父类的所有线程组中线程的个数
groupA.enumerate(tga);//enumerate将构成调用线程组的线程放入tga数组中
for(int i=0;i<tga.length;++i)
{
((newThread)tga[i]).mysuspend();//暂停每一个线程
}
try
{
Thread.sleep(4000);
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}System.out.println("Resuming Group A");
for(int i=0;i<tga.length;++i)
{
((newThread)tga[i]).myresume();
}
System.out.println("Waiting for threads to finish.");
try
{
ob1.join();
ob2.join();
ob3.join();
ob4.join();
}
catch(InterruptedException e)
{
System.out.println("Exception in main thread");
}
System.out.println("Main thread exiting");
}
}
class newThread extends Thread
{
boolean suspendFlag;
newThread(String threadname,ThreadGroup tgOb)
{
super(tgOb,threadname);
System.out.println("New Thread:"+this);
suspendFlag=false;
start();
}
public void run()
{
try
{
for(int i=5;i>0;i--)
{
System.out.println(getName()+":"+i);
Thread.sleep(1000);
synchronized(this)
{
while(suspendFlag=true)
{
wait();
}
}
}
}
catch(Exception e)
{
System.out.println("Exception in "+getName());
}
System.out.println(getName()+"exiting");
}
public void mysuspend()
{
suspendFlag=true;
}
public synchronized void myresume()
{
suspendFlag=false;
notify();
}
}