AtomicInteger可以替换同步吗? [英] Can AtomicInteger replace synchronized?

查看:107
本文介绍了AtomicInteger可以替换同步吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java.util.concurrent.atomic包的javadoc说明如下:

The javadoc for the java.util.concurrent.atomic package says the following:


$ b $类的小工具包b支持对单个变量进行无锁线程安全
编程。

A small toolkit of classes that support lock-free thread-safe programming on single variables.

但我看不到任何线程安全(同步或锁定)代码在任何AtomicInteger或AtomicBoolean类中。

But I don't see any thread-safe (synchronized or Lock) code inside any of the AtomicInteger or AtomicBoolean classes.

所以,这两个是相同的:


1.

So, are these 2 the same:

1.

int i;
synchronized(this){i++;}

2。

AtomicInteger i = new AtomicInteger();
i.getAndIncrement();

更新:感谢您的回答。当我使用AtomicInteger时需要volatile吗?

Update: Thanks for the answers. Is volatile needed when I use AtomicInteger?

推荐答案

它们会提供相同的原子性。你必须注意的唯一事情是你读的时候你必须用同步包裹它

They would offer the same atomicity. The only thing you must be aware of is any time you read i you must wrap it with synchronized also

synchronized(this){ return i;}

编辑以回答您的编辑:

AtomicInteger不需要易失性。要证明声明AtomicInteger最终。您需要AtomicInteger易变的唯一原因是AtomicInteger字段本身是否发生变化。类似于:

Volatile is not necessary for your AtomicInteger. To prove that declare the AtomicInteger final. The only reason you would need the AtomicInteger to be volatile is if the AtomicInteger field itself changes. Similar to:

volatile AtomicInteger i = new AtomicInteger(0);

public void work(){
    i.incrementAndGet();
    //...do some other stuff
    i = new AtomicInteger(10);//because the field i is changing the field needs to be volatile 
}

你可以想象不应该这样,所以你不必担心这个领域是不稳定的。

As you can imagine that shouldn't be the case, so you shouldn't have to worry about the field being volatile.

这篇关于AtomicInteger可以替换同步吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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