Java Reference
In-Depth Information
Chapter 16
Threads
WHAT YOU WILL LEARN IN THIS CHAPTER
• What a thread is and how to create threads in your programs
• How to control interactions between threads
• What synchronization means and how to apply it in your code
• What deadlocks are and how to avoid them
• What an executor is and how to use an executor to start and manage threads
• How to create threads that return a value
• How to set thread priorities
In this chapter you investigate the Java facilities that enable you to overlap the execution of segments of a
single program. As well as ensuring your programs run more efficiently, this capability is particularly useful
when your program must, of necessity, do a number of things at the same time: for example, a server pro-
gram on a network that needs to communicate with multiple clients. As you see in Chapter 18, threads are
also fundamental to any Java application that uses a graphical user interface (GUI), so it's essential that you
understand how threads work.
UNDERSTANDING THREADS
Most programs of a reasonably large size contain some code segments that are more or less independent of
one another and that might execute more efficiently if the code segments could be overlapped in time. Threads
provide a way to do this. A thread of execution is a serial sequence of instructions that is reasonably inde-
pendent of other code segments in a program so its execution can be controlled independently. If you have
a machine with two or more processors then as many computations as you have processors can be executing
concurrently. This allows the possibility for more than one program to be executing at any given instant. It
also allows multiple threads of execution in a single program to be executing at the same time. All the pro-
gram examples you have seen so far in the topic consist of a single thread of execution. Graphical applications
have two or more threads. Other kinds of applications can benefit from having more than one thread.
Of course, if your computer has only one processor, you can't execute more than one computation at any
instant, but you can still overlap input/output operations with processing. You can also have multiple threads
in progress at one time. In this case the operating system manages the transfer of execution control between
them and determines when each thread gets access to the processor and for how long.
Using threads you can allow processes in a program that need to run continuously, such as a continuously
running animation, to be overlapped with other activities in the same program. Java applets in a web page are
Search WWH ::




Custom Search