如果多个线程正在更新同一个变量,应该怎么做才能使每个线程正确更新该变量? [英] if multiple threads are updating the same variable, what should be done so each thread updates the variable correctly?
问题描述
如果多个线程正在更新同一个变量,那么每个线程应该正确更新该变量怎么办?
If multiple threads are updating the same variable, what should I do so each thread updates the variable correctly?
任何帮助将不胜感激
推荐答案
有几种选择:
1)完全不使用同步
仅当数据为原始类型(不是长/双精度)并且您不关心读取过时的值(这不太可能)时,此方法才有效
This can only work if the data is of primitive type (not long/double), and you don't care about reading stale values (which is unlikely)
2)将字段声明为易变
这将确保永远不会读取过时的值.它也可以很好地用于对象(假设对象在创建后未更改),因为在保证可变变量之前(请参阅"Java内存模型"),这是偶然发生的.
This will guarantee that stale values are never read. It also works fine for objects (assuming the objects aren't changed after creation), because of the happens-before guarantees of volatile variables (See "Java Memory Model").
3)使用java.util.concurrent.AtomicLong,AtomicInteger等
它们都是线程安全的,并且支持特殊操作,例如原子增量和原子比较并设置操作.
They are all thread safe, and support special operations like atomic incrementation and atomic compare-and-set operations.
4)保护具有相同锁定的读取和写入
这种方法提供了互斥性,这允许定义一个较大的原子操作,其中将多个数据成员作为一个操作进行操作.
This approach provides mutual exclusion, which allows defining a large atomic operation, where multiple data members are manipulated as a single operation.
这篇关于如果多个线程正在更新同一个变量,应该怎么做才能使每个线程正确更新该变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!