Java Reference
In-Depth Information
The numbers on the arrows in the figure indicate the sequence of events.
No!
indicates that the thread
waits until the method is unlocked so it can execute it. While
method1()
in
obj2
is executing,
method2()
for the same object can't be executed. The synchronization of these two instance methods in an object
provides a degree of protection for the object, in that only one synchronized method can mess with the data
in the object at any given time.
However, each object is independent of any other object when it comes to synchronized instance meth-
ods. When a thread executes a synchronized method for an object, it is assured exclusive access to the ob-
ject insofar as the synchronized methods in that object are concerned. Another thread, though, can still call
the same method for a different object. While
method1()
is being executed for
obj1
, this doesn't prevent
method1()
for
obj2
being executed by some other thread. Also, if there's a method in an object that has not
been declared as
synchronized
—
method3()
in
obj1
, for example — any thread can call that at any time,
regardless of the state of any synchronized methods in the object.
If you apply synchronization to
static
methods in a class, only one of those
static
methods in the class
can be executing at any point in time; this is per-class synchronization, and the class lock is independent of
any locks for objects of the class.
An important principle that you need to understand is that only the
run()
method is necessarily part of
a thread of execution in a class object that represents a thread. Other methods for the same class object are
only part of the thread of execution if they are called directly or indirectly by the
run()
method. All the
methods that are called directly or indirectly from the
run()
method for an object are all part of the same
thread, but they clearly don't have to be methods for the same
Thread
object. Indeed, they can be methods
that belong to any other objects, including other
Thread
objects that have their own
run()
methods.
Using Synchronized Methods
To see how synchronization can be applied in practice, you construct a program that provides a simple model
of a bank. This particular bank is a very young business with only one customer account initially, but you
have two clerks, each working flat out to process transactions for the account, one handling debits and the
other handling credits. The objects in the program are illustrated in
Figure 16-7
.