Java Reference
In-Depth Information
thread1
thread2
thread3
run(){
run(){
run(){
obj1.method2()
obj1.method3()
obj1.method1()
obj2.method1()
}
obj2.method3()
obj2.method2()
}
}
3
1
4
5
obj1
2
obj2
6
OK.
method2()
synchronized
method1()
synchronized
method1()
not busy
No!
synchronized
method2()
synchronized
method2()
Not while
for
method2()
obj1
is executing
OK.
Always
OK
method3()
method3()
method1()
Always
OK
not busy
No!
Not while
for
method1()
obj2
is executing
The numbers on the arrows in the diagram 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
methods. When a thread executes a synchronized method for an object, it is assured exclusive access to
the object 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, and this is per class synchronization and the class lock is
independent of any locks for objects of the class.
An important point of principle that you need to understand is that the only method that is necessarily
part of a thread in a class object that represents a thread is the
run()
method. Other methods for the
same class object are only part of the thread 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.