Java Reference
In-Depth Information
CHAPTER 4
■ ■ ■
Threading
W
elcome to threading. In this chapter we will demystify this topic by breaking it down into
manageable sections and subsections using real-world examples and metaphors. The purpose
of this chapter is to explain the conceptual and technical details you need to pass the SCJD
exam, including the written part of the exam.
The first sections of this chapter introduce threading and the challenges of multithread-
ing. Waiting is explained in detail, as is locking. Finally, there is a subsection on thread safety
issues, including deadlocks, starvation, race conditions, and monitors.
The sections that follow discuss the various ways that
Thread
objects can be used directly,
considerations of threading when working with Swing, and the dos and don'ts of threading.
Finally, we'll conclude with a FAQ section that covers some common threading questions.
Specifically the following topics are covered:
•
An introduction to threads and multithreading
•
Locking and synchronization
•
The new locking capabilities of JDK 5
•
Effective thread management through waiting, sleeping, and yielding
•
The importance of thread safety
•
Record-locking strategies
■
Note
This chapter is only designed to be an introduction to threading. If you want to gain an in-depth
understanding of threading, we recommend Allen Holub's excellent topic,
Taming Java Threads
(Apress,
2000).
Threading Fundamentals
Before you start this chapter, there are few things you should already know about threads. You
should know that there are two ways to create a thread of execution in Java: the first by extend-
ing the
Thread
object, and the second by implementing the
Runnable
interface. You should
know that to start a thread you must call the
start
method, and you should know that threads
71