Thread
Thread
The runtime environment distinguishes between user threads and daemon threads. As
long as a user thread is alive, the JVM does not terminate. A daemon thread is at the
mercy of the runtime system: it is stopped if there are no more user threads running, thus
terminating the program. Daemon threads exist only to serve user threads.
When a standalone application is run, a user thread is automatically created to execute the
main() method. This thread is called the main thread. If no other user threads are
spawned, the program terminates when the main() method finishes executing. All other
threads, called child threads, are spawned from the main thread, inheriting its user-thread
status. The main() method can then finish, but the program will keep running until all the
user threads have finished. Calling the setDaemon(boolean) method in the Thread class
marks the status of the thread as either daemon or user, but this must be done before the
thread is started. Any attempt to change the status after the thread has been started,
throws an IllegalThreadStateException. Marking all spawned threads as daemon
threads ensures that the application terminates when the main thread dies.
Thread Creation