How can I increment a variable without exceeding a maximum value?

前端 未结 14 1561
别跟我提以往
别跟我提以往 2021-01-30 12:03

I am working on a simple video game program for school and I have created a method where the player gets 15 health points if that method is called. I have to keep the health at

14条回答
  •  清酒与你
    2021-01-30 12:43

    If I wanted to be thread safe I'd do it this way rather than using a synchronized block.

    The atomic compareAndSet achieves the same outcome as synchronized without the overhead.

    AtomicInteger health = new AtomicInteger();
    
    public void addHealth(int value)
    {
        int original = 0;
        int newValue = 0;
        do
        {
            original = health.get();
            newValue = Math.min(100, original + value);
        }
        while (!health.compareAndSet(original, newValue));
    }
    

提交回复
热议问题