This question is proabaly better suited for the
Threads and Synchronization forum. I'm sure a bartender will kindly move it over there for us.
Originally posted by Pawel Nowacki:
that makes only one thread (always first to start) allowed to call makeWithdrawal.
It won't always be the first one. This is simply what is happening on your PC based on what you are doing. For example, on my PC I was seeing Fred go first. But then by doing this:
in the main method, enough of a delay was introduced that I started seeing Lucy first "all" the time.
Basically, the reason you are seeing the one thread do all its transactions first is that the work is run fast enough that the one thread completes before the thread scheduler gives the second thread a go at it and it is able to do some work. For example, change loop so it loops through 200 times:
Also, increase the initial balance to 1000 so you can see the withdraws ping pong between the two users before the overdrafts start.
Run that and you will eventually see the second thread gets a go at it and the withdraw attempts will bounce between Lucy and Fred.
So it's not so much your JDK, but the speed of of CPU and the behavior of the Thread scheduler on your machine.
Keep in mind, simulating threading behavior and delays is very hard; especially on small scales.
Another thing you can do, is introduce a delay in the withdraw method so that the other thread is given a chance. Here I use a random delay to more simulate potential real behavior. The key is this: it must at some point sleep for longer than the 1000 ms delay when simulating the withdraw. By using a random time, it prevents always seeing Fred, Lucy, Fed Lucy, Fred Lucy... all the way through on every run.
This isn't the best way to to do things in production code. But for an example and simulation, it works.