的AtomicBoolean VS synchronized块,什么区别 [英] AtomicBoolean vs Synchronized block, whats the difference

查看:418
本文介绍了的AtomicBoolean VS synchronized块,什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解两者的区别如下code块

I am trying to understand the difference between the two following code blocks

AtomicBoolean ab = new AtomicBoolean(false);  

using the following to get and set state. .
ab.get();
ab.set(X);

vs. 

private boolean ab = false;
private final Object myboollock = new Ojbect();

public void setAB(boolean state)
{
    synchronized(myboollock)
     {
          ab = state;
     }
}

public boolean getAB()
{
 synchronized(myboollock)
 {
         return ab;
 }
}

我需要线程保护一个布尔值,这是所有,并有
在过去使用的后一种方法,但想开始使用原子
对象,(如果)他们是安全的?

I need to thread protect a boolean, that is all, and have in the past used the later method, but would like to start to use Atomic objects, (if ) they are safe?,

推荐答案

有一些细微的差别,但是从两个code段外的行为类似看出:如果调用设置方法,这种变化将是其他线程调用可见 GET 其后。

There are a few subtle differences but seen from the outside the two code snippets behave similarly: if you call the set method, the change will be visible to other threads calling get subsequently.

的主要区别是:


  • 性能:根据争的水平,你可以用同步的AtomicBoolean
  • 原子性:如果在某个阶段你想要做的不仅仅是设置布尔值,同步块将允许您原子加指令,但的AtomicBoolean 不会

  • performance: depending on the level of contention, you may get better performance with synchronized or AtomicBoolean
  • atomicity: if at some stage you want to do more than just setting the boolean value, a synchronized block will allow you to add instructions atomically but AtomicBoolean won't

这篇关于的AtomicBoolean VS synchronized块,什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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