Can someone have a look at this sample code from Osborne's
Java 2: The Complete Reference, and anser my question at the end of this post? The
code is question is marked in red.
I need an explanation on the following code snippet from Osborne's
Java 2: The Complete Reference. This code appears as an example of
ThreadGroup. I think the simplest thing to do is post all of the
code, then ask my question. Here it is:
class NewThread extends
Thread {
boolean suspendFlag ;
NewThread (
String threadname, ThreadGroup tgobj )
{
super ( tgobj, 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 )
{
wait() ;
}
}
}
catch ( Exception e )
{
System.out.println( "Exception in "+ getName() ) ;
}
System.out.println( getName() + " exiting." ) ;
}
void mysuspend()
{
suspendFlag = true ;
}
synchronized void myresume()
{
suspendFlag = false ;
notify() ;
}
}
class ThreadGroupDemo
{
public static void main( String args[] )
{
ThreadGroup groupA = new ThreadGroup( "Group A" ) ;
ThreadGroup groupB = new ThreadGroup( "Group B" ) ;
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() ;
groupB.list() ;
System.out.println() ;
System.out.println( "Suspending Group A" ) ;
Thread tga[] = new Thread[ groupA.activeCount() ] ;
groupA.enumerate( tga ) ;
for( int i = 0 ; i < tga.length ; i++ )
{
( (NewThread)tga[ i ] ).mysuspend() ;
}
<font color=red>
try
{
Thread.sleep( 4000 ) ;
}
catch ( InterruptedException e )
{
System.out.println( "Main thread interrupted." ) ;
}
</font>
System.out.println( "Resuming Group A" ) ;
for( int i = 0 ; i < tga.length ; i++ )
{
( (NewThread)tga[ i ] ).myresume() ;
}
try
{
System.out.println( "Waiting for threads to finish." ) ;
ob1.join() ;
ob2.join() ;
ob3.join() ;
ob4.join() ;
}
catch ( Exception e )
{
System.out.println( "Exception in Main thread" ) ;
}
System.out.println( "Main thread exiting." ) ;
}
}
How does Thread.sleep( 4000 ) know to suspend only the threads in Group A? This bit of code runs after Group A has been suspended by a call to wait() from run(), but I don't see how Thread.sleep( 4000 ) knows which threads to act on. Why doesn't it suspend all threads?
