Java 线程安全中的 volatile int 是什么? [英] Is a volatile int in Java thread-safe?

查看:33
本文介绍了Java 线程安全中的 volatile int 是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 线程安全中的易失性 int 吗?也就是说,可以在不加锁的情况下安全地读取和写入吗?

Is a volatile int in Java thread-safe? That is, can it be safely read from and written to without locking?

推荐答案

是的,您可以安全地从中读取和写入 - 但是您不能执行任何复合操作,例如安全地递增它,因为那是读取/修改/写循环.还有一个问题是它如何与对其他变量的访问进行交互.

Yes, you can read from it and write to it safely - but you can't do anything compound such as incrementing it safely, as that's a read/modify/write cycle. There's also the matter of how it interacts with access to other variables.

坦率地说,volatile 的确切性质令人困惑(请参阅 JLS 的内存模型部分以获取更多详细信息) - 我个人通常会使用 AtomicInteger,作为一种更简单的方法来确保我做对了.

The precise nature of volatile is frankly confusing (see the memory model section of the JLS for more details) - I would personally generally use AtomicInteger instead, as a simpler way of making sure I get it right.

这篇关于Java 线程安全中的 volatile int 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆