Java Reference
In-Depth Information
14.9. Ending Application Execution
Each application starts with one threadthe one that executes main . If your
application creates no other threads, the application will finish when main
returns. But if you create other threads, what happens to them when main
returns?
There are two kinds of threads: user and daemon. The presence of a user
thread keeps the application running, whereas a daemon thread is ex-
pendable. When the last user thread is finished, any daemon threads are
terminated and the application is finished. This termination is like that
of invoking destro yabrupt and with no chance for any cleanupso daemon
threads are limited in what they can do. You use the method setDae-
mon(true) to mark a thread as a daemon thread, and you use isDaemon to
test that flag. By default, daemon status is inherited from the thread that
creates the new thread and cannot be changed after a thread is started;
an IllegalThreadStateException is thrown if you try.
If your main method spawns a thread, that thread inherits the user-thread
status of the original thread. When main finishes, the application will con-
tinue to run until the other thread finishes, too. There is nothing special
about the original threadit just happened to be the first one to get started
for a particular run of an application, and it is treated just like any other
user thread. An application will run until all user threads have completed.
For all the runtime system knows, the original thread was designed to
spawn another thread and die, letting the spawned thread do the real
work. If you want your application to exit when the original thread dies,
you can mark all the threads you create as daemon threads.
You can force an application to end by invoking either the System or
Runtime method exit . This method terminates the current execution of the
Java virtual machine and again is like invoking destroy on each thread.
However, an application can install special threads to be run before the
application shuts downthe methods for doing this are described in " Shut-
down " on page 672 .
 
Search WWH ::




Custom Search