posted 20 years ago
Here's a bit of code:
Here's a block which uses the code:
The output of that block could well look like this;
One: Before synchronization 1
Two: Before synchronization 1
One: Before synchronization 2
Two: Before synchronization 2
Two: Started some work...
One: Started some work...
One: ...working...
Two: ...working...
Two: Finishing the work...
Two: After synchronization 1
One: Finishing the work...
One: After synchronization 1
One: After synchronization 2
Two: After synchronization 2
As you can see, there's nothing at all stopping both instances of SynchronizedRunnable from executing the code in the synchronized block as the same time. The reason is that they're using two different locks. If you change the code to
Then you the lines "Started some work...", "...working...", and "Finishing the work..." will always appear right next to each other, because only on the the threads can hold the lock at any given time. Just another random sample output for this version:
Two: Before synchronization 1
One: Before synchronization 1
One: Before synchronization 2
Two: Before synchronization 2
Two: Started some work...
Two: ...working...
Two: Finishing the work...
One: Started some work...
One: ...working...
Two: After synchronization 1
One: Finishing the work...
One: After synchronization 1
One: After synchronization 2
Two: After synchronization 2
You can see that the synchronized sections do not overlap, although code outside the synchronized block may execute while other code is in the synchronized block (here that happened with "Two: After synchronization 1")