Java 中 .Net 的 Interlocked 类的等价物是什么?
如何在 Java 中原子地且线程安全地修改 int?
原子增量、测试和 设置等...?
How do I modify an int atomically and thread-safely in Java?
Atomically increment, test & set, etc...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用AtomicInteger。
Use AtomicInteger.
线程安全可以通过同步函数来实现。
将您的 int (或此类数据)包装在一个类中,该类通过同步方法提供所需的功能,例如
您还可以使用 java.util.concurrent.atomic 包,例如 AtomicInteger 或 AtomicIntegerArray
为什么这个答案不起作用
我只是想要确保指出这个答案到底有什么问题,以防有人认为
synchronized
可用于解决线程竞争效应。操作的最终结果
是:x = 5 而不是 6。
volatile
关键字也存在同样的问题。volatile
关键字并不能避免线程效应。 易失性关键字仅确保严格来说,
易失性
确保内存操作不会围绕易失性变量重新排序。 这意味着您仍然遭受:问题。
Thread safety can be achieved via synchronized functions.
Wrap your int (or such data) in a class which provides the required functionalities via synchronized methods, e.g.
You can also use classes from the java.util.concurrent.atomic package, e.g. AtomicInteger or AtomicIntegerArray
Why this answer won't work
I just wanted to be sure to point out exactly what is wrong with this answer, in case anyone thinks that
synchronized
can be used to solve thread race effects.The end result of the operations:
is that x = 5 rather than 6.
The same issue exists with the
volatile
keyword. Thevolatile
keyword doesn't save you from thread effects. The volatile keyword only ensures thatStrictly speaking,
volatile
ensures that memory operations are not reordered around a volatile variable. Which means you still suffer from the:problem.