Java中的Atomic Integer和Normal不可变Integer类有什么区别? [英] What is the difference between Atomic Integer and Normal immutable Integer class in Java?

查看:321
本文介绍了Java中的Atomic Integer和Normal不可变Integer类有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Integer类也是不可变的类,并且我们知道不可变的类是线程安全的,因此Atomic Integer的需求是什么. 我很迷惑 . 这是因为不可变对象的读取和写入不必是原子的,而原子整数的读取和写入是atomic的原因. 这意味着原子类也是线程安全的.

As Integer class is also immutable class and we know that immutable class is thread-safe what is the need of Atomic Integer. I am confused . Is it the reason that reads and write of immutable objects need not be atomic whereas read and write of atomic integer is atomic . That means atomic classes are also thread-safe.

推荐答案

在需要确保只有一个线程可以更新int变量的情况下,AtomicInteger用于多线程环境.优点是不需要外部同步,因为修改其值的操作是以线程安全的方式执行的.

AtomicInteger is used in multithreaded environments when you need to make sure that only one thread can update an int variable. The advantage is that no external synchronization is requried since the operations which modify it's value are executed in a thread-safe way.

考虑以下代码:

private int count;

public int updateCounter() {
   return ++count;
}

如果多个线程将调用updateCounter方法,则其中某些线程可能会收到相同的值. ++ count操作不是原子操作的原因不仅是一个操作,还包括以下三个操作:read count, add 1 to it's value and write it back to it.多个调用线程可能会将该变量视为未修改为其最新值.

If multiple threads would call the updateCounter method, it's possible that some of them would receive the same value. The reason it that the ++count operation isn't atomical since isn't only one operation, but made from three operations: read count, add 1 to it's value and write it back to it. Multiple calling threads could see the variable as unmodified to it's latest value.

上面的代码应替换为:

private AtomicInteger count = new AtomicInteger(0);
public int updateCounter() {
    return count.incrementAndGet();
}

incrementAndGet方法保证在不使用任何外部同步的情况下原子地增加存储的值并返回其值.

The incrementAndGet method is guaranteed to atomically increment the stored value and return it's value without using any external synchonization.

如果您的值永远不变,则不必使用AtomicInteger,就足以使用int.

If your value never changes, you don't have to use the AtomicInteger, it's enought to use int.

这篇关于Java中的Atomic Integer和Normal不可变Integer类有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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