Types of Threads – Concurrency: Part I

Types of Threads

The runtime environment distinguishes between normal threads (also called user threads) and daemon threads. As long as a normal thread is alive—meaning that it has not completed executing its task—the JVM does not terminate. A daemon thread is at the mercy of the runtime system: It is stopped if no more normal threads are running, thus terminating the program. Daemon threads exist only to serve normal threads. It is not a good strategy to run any clean-up code in daemon threads, which might not get executed if a daemon thread is stopped.

Uncommenting the statements at (7) in Example 22.2:

Click here to view code image

counterA.setDaemon(true);
counterB.setDaemon(true);

illustrates the daemon nature of threads. The program execution will now terminate after the main thread has completed, without waiting for the daemon Counter threads to finish normally:

Click here to view code image

Method main() runs in thread main
Starting Counter A
Starting Counter B
Counter A: 0
Counter B: 0
Exiting main

When a standalone application is run, a normal thread is automatically created to execute the main() method of the application. This thread is called the main thread. If no other normal 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 normal-thread status. The main() method can then finish, but the program will keep running until all normal threads have completed. The status of a spawned thread can be set as either daemon or normal, but this must be done before the thread is started. Any attempt to change the status after the thread has been started throws an unchecked IllegalThreadState-Exception. A child thread inherits the thread status of its parent thread.

When a GUI application is started, a special thread is automatically created to monitor the user–GUI interaction. This normal thread keeps the program running, allowing interaction between the user and the GUI, even though the main thread might have completed after the main() method finished executing.

Leave a Reply

Your email address will not be published. Required fields are marked *