[ Team LiB ] Previous Section Next Section

Chapter 4. Threads

A thread is a unit of program execution that runs independently from other threads. Java programs may consist of multiple threads of execution that behave as if they were running on independent CPUs, even when the host computer actually has only a single CPU. In many programming languages, multithreading capabilities are added on as an afterthought. In Java, however, they are integrated tightly with the language and its core packages:

  • The java.lang.Runnable interface defines a run( ) method that serves as the block of code a thread executes. When that method exits, the thread stops running.

  • The java.lang.Thread class represents a thread; it defines methods for setting and querying thread properties (such as execution priority level) and for starting the execution of a thread.

  • The synchronized statement and modifier can be used to write blocks of code or entire methods that require a thread to obtain a lock before executing the block or the method. This mechanism ensures that two threads can't run the block or method at the same time, to avoid problems with different threads putting shared data in an inconsistent state.

  • The wait( ) and notify( ) methods of java.lang.Object can be used to suspend threads and wake them up again.

The use of threads is common in Java programming; it is not possible to confine a discussion of them to just one chapter. We'll start with some simple examples in this chapter. We'll see threads again in Chapter 5, where they are quite useful for writing network server programs that can respond to multiple client requests simultaneously. Threads also appear in Chapter 12, and then again in Chapter 16, where they are used to produce animation effects.

    [ Team LiB ] Previous Section Next Section