Probably, I should try to explain with a scenario
Lets say there is a bus with 20 tickets available.
There is a list of 5 people.
There are two threads named Avi and Campbell.
Avi starts first and then Campbell.
Avi checks the number of tickets in the static variable. Oh, we got 20 tickets and 20 >= 5 for sure, so i should book the first person in the list.
I go into the loop, take the first person, puts in the register saying hey you got 5 tickets. congrats. booked by Avi. As method is synchronized, Campbell is still outside the method
waiting for Avi to get out. Once i booked the person-0, i come out of the door, put the key in the nearby key holder.
Campbell gets the key and gets inside the method and checks the static variable. Aha, 15 more tickets, I should book a person. You go in, takes the name from the list, not sure
how you will get to Person-1, still a mystery for me
, and then book him. You then reduce the number of tickets to 15-5 = 10, comes out of the method, keep the key in the key holder.
That is what I want to do. It seems my code is definitely not doing that. I am not able to think of a design to do that.
Any advice will be appreciated.
Why static variable is a bad idea? Not sure though. But i checked that When Avi goes out of method after putting Person-0, Campbell still sees Person-0 and so it puts the Person-0 in list again.
Probably, i am not designing the threads properly.