0% found this document useful (0 votes)
45 views

Thread

The main thread refers to the thread that is automatically created to execute the main() method when a standalone application runs. As long as any user thread is alive, the JVM will not terminate the program. Daemon threads exist only to serve user threads and the program will terminate when only daemon threads remain active. The status of a thread as a daemon or user thread must be set before it is started.

Uploaded by

api-3831588
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Thread

The main thread refers to the thread that is automatically created to execute the main() method when a standalone application runs. As long as any user thread is alive, the JVM will not terminate the program. Daemon threads exist only to serve user threads and the program will terminate when only daemon threads remain active. The status of a thread as a daemon or user thread must be set before it is started.

Uploaded by

api-3831588
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 1

The Main 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

A thread in Java is represented by an object of the Thread class. Implementing threads is


achieved in one of two ways:

• implementing the java.lang.Runnable interface


• extending the java.lang.Thread class

You might also like