Java Reference
In-Depth Information
Hopalong Monroe
Marilyn Pickens
Slim Cassidy
Hopalong Monroe
Marilyn Cassidy
Hopalong Cassidy
Hopalong Monroe
Marilyn Pickens
Slim Cassidy
Hopalong Cassidy
Hopalong Monroe
Marilyn
Enter pressed...
Ending main()
How It Works
You have three instance variables in the
TryThread
class, and these are initialized in the constructor.
The two
String
variables hold first and second names, and the variable
aWhile
stores a time period
in milliseconds. The constructor for the class,
TryThread()
,automatically calls the default constructor,
Thread()
, for the base class.
The class containing the
main()
method is derived from
Thread
and implements
run()
, so objects of
this class represent threads. The fact that each object of your class has access to the method
main()
is ir-
relevant — the objects are perfectly good threads. The method
main()
creates three such objects:
first
,
second
, and
third
.
Daemon and User Threads
The call to
setDaemon()
, with the argument
true
in the
TryThread
constructor, makes the thread that is
created a
daemon thread
. A daemon thread is simply a background thread that is subordinate to the thread
that creates it, so when the thread that created it ends, the daemon thread dies with it. In this case, the
main()
method creates the daemon threads so that when
main()
returns and ends the main thread, all the threads it
has created also end. If you run the example a few times pressing Enter at random, you should see that the
daemon threads die after the
main()
method returns, because, from time to time, you get some output from
one or another thread after the last output from
main()
.
A thread that isn't a daemon thread is called a
userthread
. The diagram in
Figure 16-4
shows two daemon
threads and a user thread that are created by the main thread of a program.