Java Reference
In-Depth Information
Our class containing the method main() is derived from Thread , and implements run() , so objects
of this class represent threads. The fact that each object of our class will have access to the method
main() is irrelevant - the objects are perfectly good threads. Our 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 the daemon thread ends, the daemon thread
dies with it. In our case, the method main() creates the daemon threads so that when main() returns,
all the threads it has created will 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 will get some output from one or other thread after the last output from main() .
A thread that isn't a daemon thread is called a user thread . The diagram below shows two daemon
threads and a user thread that are created by the main thread of a program.
thread1
Starts a daemon thread.
will die automatically
when the main thread ends
Main Thread
thread1
created as a
daemon thread
user thread by default
Daemon threads can be
continuous loops as they will be
destroyed automatically
when their creator ends
thread1.setDaemon(true);
thread1.start();
thread2.setDaemon(true);
thread2.start();
thread3.start();
return;
thread2
Starts a daemon thread.
will die automatically
when the main thread ends
thread2
created as a
daemon thread
Ends the main thread. All daemon
threads created in the main thread
will end at this point
thread3
Starts a user thread.
can continue executing
after the main thread ends
A user thread must be
explicitly stopped or destroyed,
or its run method must return
thread3
created as a
user thread
A user thread has a life of its own that is not dependent on the thread that creates it. It can continue execution
after the thread that created it has ended. The default thread that contains main() is a user thread, as shown
in the diagram, but thread3 shown in the diagram could continue to execute after main() has returned.
Threads that run for a finite time are typically user threads, but there's no reason why a daemon thread can't
be finite. Threads that run indefinitely should usually be defined as daemon threads simply because you need
a means of stopping them. A hypothetical example might help you to understand this so let's consider how a
network server handling transactions of some kind might work in principle.
Search WWH ::




Custom Search