Objectives This chapter is an introduction to concurrent, or multi-threaded, programming.
We will discuss the mechanisms Java provides to support concurrent programming.
The issues of synchronization and cooperation among threads will be addressed.
Contents 8.1 Threads
8.1.1 Creation of Threads
8.1.2 Controlling Threads
8.2 Thread Safety and Liveness
8.2.1 Synchronization
8.2.2 Cooperation Among Threads
8.2.3 Liveness Failures
8.3 Design Case Study: Tic-Tac-Toe Game
This example demonstrates thread creation by extending the Thread class.
This class defines a thread whose body consists of an infinite loop. It
maintains a counter, which is incremented by the amount of inc in
each iteration. Each iteration of the loop sleeps "delay" milliseconds.
This is another example that demonstrates thread creation by extending
the Thread class. The random number generation function Math.random() is
used to simulate the fluctuation of stock prices.
This example demonstrates thread creation by implementing the Runnable
interface. This class defines a thread that behaves the same as the one
in Example 8.1.
This example shows a simple bounded queue implementation that is not thread
safe. A bounded queue is a first-in-first-out queue with a fixed capacity.
The BoundedQueue class below is implemented using a circular array. The
capacity of the queue is specified by the argument to the constructor.
The capacity of the queue may not be changed.
This example demonstrates the use of synchronization to ensure thread safety.
The SyncBoundedQueue class is identical to the BoundedQueue in the previous
example, except it is fully synchronized and thread safe.
Example 8.6: The "BoundedQueueWithGuard" Application
This example demonstrates use of the wait() and notify() methods to implement
guarded suspension and ensure cooperation among threads. The BoundedQueueWithGuard
class extends the BoundedQueue class. It is fully synchronized. The put()
and get() methods are overridden to support cooperation among the producer
and the consumer.
This is a simple game: Tic-Tac-Toe. It is implemented as a two-player game
on a 3 x 3 board, however it is designed in a way that can be extended
to an k-player (k 2) game on a m x n board. This is a multi-threaded program.
Each player is a thread. Two types of players are implemented:
A human player, which waits for a human to make moves by clicking the
mouse on the game board.
A machine player, which automatically generates moves (not necessarily
good ones).