AtomicBoolean vs Synchronized block, whats the difference(AtomicBoolean vs Synchronized block,有什么区别)
问题描述
我试图了解以下两个代码块之间的区别
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;
 }
}
我需要线程保护一个布尔值,仅此而已,并且有以前用过后来的方法,但是想开始用Atomic对象,(如果)它们是安全的?,
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?,
推荐答案
这两个代码片段有一些细微的差别,但从外观上看是相似的:如果你调用 set 方法,随后调用 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.
主要区别在于:
- 性能:根据争用的级别,您可能会使用 synchronized或AtomicBoolean获得更好的性能
- 原子性:如果在某个阶段您想做的不仅仅是设置布尔值,synchronized块将允许您以原子方式添加指令,但AtomicBoolean不会
- performance: depending on the level of contention, you may get better performance with synchronizedorAtomicBoolean
- atomicity: if at some stage you want to do more than just setting the boolean value, a synchronizedblock will allow you to add instructions atomically butAtomicBooleanwon't
这篇关于AtomicBoolean vs Synchronized block,有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:AtomicBoolean vs Synchronized block,有什么区别
 
				
         
 
            
        基础教程推荐
- Java Swing计时器未清除 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 大摇大摆的枚举 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				