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

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

问题描述

Java线程安全中是volatile 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天全站免登陆