Java Reference
In-Depth Information
"to die.");
try
{
thd.join();
}
catch (InterruptedException ie)
{
}
System.out.println("Main thread is dying");
}
}
Listing4-19
demonstratesthedefaultmainthreadstartingaworkerthread,perform-
ing some work, and then waiting for the worker thread to die by calling
join()
via
theworkerthread's
thd
object.Whenyourunthisapplication,youwilldiscoveroutput
similar to the following (message order might differ somewhat):
Default main thread is doing work.
Worker thread is simulating work by sleeping for 5 seconds.
Default main thread has finished its work.
Default main thread is waiting for worker thread to die.
Worker thread is dying
Main thread is dying
Every
Thread
objectbelongstosome
ThreadGroup
object;
Thread
declaresa
ThreadGroup getThreadGroup()
method that returns this object. You should
ignore thread groups because they are not that useful. If you need to logically group
Thread
objects, you should use an array or collection instead.
Caution
Various
ThreadGroup
methods are flawed. For example,
int enu-
merate(Thread[] threads)
will not include all active threads in its enumer-
ation when its
threads
array argument is too small to store their
Thread
objects.
Although you might think that you could use the return value from the
int act-
iveCount()
method to properly size this array, there is no guarantee that the array
willbelargeenoughbecause
activeCount()
'sreturnvaluefluctuateswiththecre-
ation and death of threads.
However, you should still know about
ThreadGroup
because of its contribution
in handling exceptions that are thrown while a thread is executing.
Listing 4-20
sets