Dishi Jain wrote: Sometimes the loop ends with account number value = 2000 but sometimes it ends with value less than 2000 for eg. 1999.
According to me every time the last running thread should stop with account number value = 2000 but no less.
The place to focus on here is this line...
Basically, the getNumber() method is synchronized, and hence, the call to the method is atomic; the setNumber() method is synchronized, and hence, the call to the method is atomic.
However, there is no synchronization that spans both calls simultaneously, and hence, the complete expression is not guaranteed to be atomic. It is possible for one thread to read a number (say number 42), increment it, but before it can set the new number (43), the other thread reads the same number 42.
Henry