Ruben Soto wrote:The reason why it works now is because there is only one lock involved (the lock for the shared Shared instance.)
Edit: I just took another look at your code. What output are you expecting, and what output are you getting? To make things more interesting, print the id of the thread after each print() invocation in the for() loop and see what you get.
Hi Ruben,
Earlier, i was getting the following output despite of sing the
word synchronized. I was using it at the wrong place and was getting the following output:
Output for above code:
Thread[Thread-0,5,main] Before
Thread[Thread-1,5,main] Before
Thread[Thread-1,5,main] a = 2
Thread[Thread-0,5,main] a = 3
Thread[Thread-1,5,main] After
Thread[Thread-0,5,main] After
instead of this output:(expected)
Thread[Thread-0,5,main] Before
Thread[Thread-1,5,main] a = 2
Thread[Thread-1,5,main] After
Thread[Thread-1,5,main] Before
Thread[Thread-0,5,main] a = 3
Thread[Thread-0,5,main] After
Now i understood concept.
Thanks all!! But more inputs/explanations are welcome..