原子操作和多线程

编程入门 行业动态 更新时间:2024-10-27 08:29:55
本文介绍了原子操作和多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

最近我正在阅读一个教程,因为我遇到了一个声明,说明了..

Recently I was reading a tutorial, in that I came across a statement that says..

Java语言规范保证读取或写入变量是一个原子操作(除非变量的类型为 long 或 double )。类型为的操作变量long 或 double 只有在使用 volatile 关键字声明时才是原子的。

"The Java language specification guarantees that reading or writing a variable is an atomic operation(unless the variable is of type long or double). Operations variables of type long or double are only atomic if they declared with the volatile keyword."

AtomicInteger 或 AtomicLong 提供 getAndDecrement(), getAndIncrement()和 getAndSet()这是原子的。

AtomicInteger or AtomicLong that provides methods like getAndDecrement(), getAndIncrement() and getAndSet() which are atomic.

我对上述陈述感到困惑..请你澄清何时使用 AtomicInteger 或 AtomicLong 类。

I got confused a bit with the above statement.. could you please clarify when to use AtomicInteger or AtomicLong classes.

推荐答案

执行 a = 28 ( a 是 int )是原子操作。但是,执行 a ++ 不是原子操作,因为它需要读取a的值,增量和对结果的写入。因此,如果您使用 a ++ 来实现线程安全计数器,您可以让两个线程同时读取该值(例如26),然后同时增加它和同时写它,结果是27而不是28。

Doing a = 28 (with a being an int) is an atomic operation. But doing a++ is not an atomic operation because it requires a read of the value of a, an incrementation, and a write to a of the result. As a result, if you used a++ to implement a thread-safe counter, you could have two threads reading the value concurrently (26 for example), then have both increment it and writing it concurrently, resulting in 27 as a result, instead of 28.

AtomicInteger通过提供你列出的原子操作来解决这个问题。在我的示例中,您将使用 incrementAndGet(),这将保证结束值为28而不是27。

AtomicInteger solves this issue by providing atomic operations like the ones you listed. In my example, you would use incrementAndGet() for example, which would guarantee the end value is 28 and not 27.

更多推荐

原子操作和多线程

本文发布于:2023-10-13 17:09:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1488580.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原子   多线程   操作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!