Java share a variable between two threads

后端 未结 4 2023
慢半拍i
慢半拍i 2020-12-11 01:06

I have two threads. One invokes the update method of a class that modifies a variable. Another invokes the update method of a class that reads the variable. Only one thread

4条回答
  •  星月不相逢
    2020-12-11 01:31

    If there is one and only one thread that writes to variable you can get away with making it volatile. Otherwise see the answer with AtomicInteger.

    Only volatile will work in case of only one writing thread because there is only one writing thread so it always has the right value of variable.

提交回复
热议问题