In my program I have one thread incrementing a supply variable by 2, then another thread takes a random number of supply from a supply class. The supply class can only store up to 5 values and because the sleep and supply requests are random, the supply count can increment over it's max limit.
What I'm trying to make sure is that it doesn't go over that limit.
Is there a better way to do this?
(pseudocode)
- increment supply by 2
- if supply is more than max then assign supply to max
Here is the code:
private int MAX = 5;
private int supply = 0;
public void run()
{
while(true) {
supply = supply + 2;
if(supply > MAX)
supply = MAX;
}
}