9.2 Overview of Threads


A thread is an independent sequential path of execution within a program. Many threads can run concurrently within a program. At runtime, threads in a program exist in a common memory space and can, therefore, share both data and code, that is, they are lightweight compared to processes. They also share the process running the program.

Every thread in Java is created and controlled by a unique object of the java.lang.Thread class. Often the thread and its associated Thread object are thought of as being synonymous.

Threads make the runtime environment asynchronous, allowing different tasks to be performed concurrently. Using this powerful paradigm in Java centers around understanding the following aspects of multithreaded programming:

  • creating threads and providing the code that gets executed by a thread (see Section 9.3, p. 351)

  • accessing common data and code through synchronization (see Section 9.4, p. 359).

  • transitioning between thread states (see Section 9.5, p. 366).

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.

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



A Programmer[ap]s Guide to Java Certification
A Programmer[ap]s Guide to Java Certification
ISBN: 201596148
EAN: N/A
Year: 2003
Pages: 284

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net