Hi,
I am reading the threads chapter for the first time.I tried a sample program on synchronization.Why am I getting different outputs for Example1 and Example 2. Please explain me what actually happens with the two examples.Request a
spoon feeding
Example1:
OutPut Of Example 1:
Lucyis going to withdrawl
Fredis going to withdrawl
Fredcompletes the withdrawl
Lucycompletes the withdrawl
Fredis going to withdrawl
Lucyis going to withdrawl
Fredcompletes the withdrawl
Lucycompletes the withdrawl
Fredis going to withdrawl
Lucyis going to withdrawl
Lucycompletes the withdrawl
Fredcompletes the withdrawl
Lucyis going to withdrawl
Fredis going to withdrawl
Fredcompletes the withdrawl
Lucycompletes the withdrawl
Fredis going to withdrawl
Lucyis going to withdrawl
Lucycompletes the withdrawl
Fredcompletes the withdrawl
Example2:
Output of Example2:
Lucyis going to withdrawl
Lucycompletes the withdrawl
Fredis going to withdrawl
Fredcompletes the withdrawl
Lucyis going to withdrawl
Lucycompletes the withdrawl
Fredis going to withdrawl
Fredcompletes the withdrawl
Lucyis going to withdrawl
Lucycompletes the withdrawl
No enough money in account for withdrawl Mr./Mrs.Fred0
No enough money in account for withdrawl Mr./Mrs.Lucy0
No enough money in account for withdrawl Mr./Mrs.Fred0
No enough money in account for withdrawl Mr./Mrs.Lucy0
No enough money in account for withdrawl Mr./Mrs.Fred0
Request spoon feeding on below.
You can make a subset (or indeed all) of the methods for any class object mutually exclusive, so that only
one of the methods can execute at any given time. You make methods mutually exclusive by declaring
them in the class using the keyword synchronized.
Now, only one of the synchronized methods in a class object can execute at any one time. Only when the
currently executing synchronized method for an object has ended can another synchronized method
start for the same object. The idea here is that each synchronized method has guaranteed exclusive
access to the object while it is executing, at least so far as the other synchronized methods for the class
object are concerned.
The synchronization process makes use of an internal lock that every object has associated with it. The
lock is a kind of flag that is set by a process, referred to as locking or a lock action, when a synchronized
method starts execution. Each synchronized method for an object checks to see whether the lock has
been set by another method. If it has, it will not start execution until the lock has been reset by an unlock
action. Thus, only one synchronized method can be executing at one time, because that method will
have set the lock that prevents any other synchronized method from starting.
Note that there�s no constraint here on simultaneously executing synchronized
methods for two different objects of the same class. It�s only concurrent access to any
one object that is controlled.