AtomicBoolean介绍
网上资料:
使用 AtomicBoolean 高效并发处理 “只初始化一次” 的功能要求:
1 |
private static
AtomicBoolean initialized = new AtomicBoolean( false ); |
2 |
3 |
public void
init() |
4 |
{ |
5 |
if (
initialized.compareAndSet( false , true )
) |
6 |
{ |
7 |
//
这里放置初始化代码.... |
8 |
} |
9 |
} |
普通方式:
1 |
public static
volatile
initialized = false ; |
2 |
3 |
public void
init() |
4 |
{ |
5 |
if (
initialized == false ){ |
6 |
initialized
= true ; |
7 |
//
这里初始化代码.... |
8 |
} |
9 |
} |
帮助文档:
java.util.concurrent.atomic
类 AtomicBoolean
java.lang.Objectjava.util.concurrent.atomic.AtomicBoolean
- 所有已实现的接口:
- Serializable
-
public class AtomicBoolean
- extends Object
- implements Serializable
可以用原子方式更新的 boolean
值。有关原子变量属性的描述,请参阅 java.util.concurrent.atomic
包规范。AtomicBoolean
可用在应用程序中(如以原子方式更新的标志),但不能用于替换 Boolean
。
- 从以下版本开始:
- 1.5
- 另请参见:
- 序列化表格
构造方法摘要 | |
---|---|
AtomicBoolean() 使用初始值 false 创建新的 AtomicBoolean 。 |
|
AtomicBoolean(boolean initialValue) 使用给定的初始值创建新的 AtomicBoolean 。 |
方法摘要 | |
---|---|
boolean |
compareAndSet(boolean expect, boolean update) 如果当前值 == 预期值,则以原子方式将该值设置为给定的更新值。 |
boolean |
get() 返回当前值。 |
boolean |
getAndSet(boolean newValue) 以原子方式设置为给定值,并返回以前的值。 |
void |
lazySet(boolean newValue) 最终设置为给定值。 |
void |
set(boolean newValue) 无条件地设置为给定值。 |
String |
toString() 返回当前值的字符串表示形式。 |
boolean |
weakCompareAndSet(boolean expect, boolean update) 如果当前值 == 预期值,则以原子方式将该值设置为给定的更新值。 |
从类 java.lang.Object 继承的方法 |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
构造方法详细信息 |
---|
AtomicBoolean
public AtomicBoolean(boolean initialValue)
- 使用给定的初始值创建新的
AtomicBoolean
。- 参数:
initialValue
- 初始值
AtomicBoolean
public AtomicBoolean()
- 使用初始值
false
创建新的AtomicBoolean
。
方法详细信息 |
---|
get
public final boolean get()
- 返回当前值。
-
-
- 返回:
- 当前值
compareAndSet
public final boolean compareAndSet(boolean expect, boolean update)
- 如果当前值
==
预期值,则以原子方式将该值设置为给定的更新值。 -
-
- 参数:
expect
- 预期值update
- 新值- 返回:
- 如果成功,则返回 true。返回 False 指示实际值与预期值不相等。
weakCompareAndSet
public boolean weakCompareAndSet(boolean expect, boolean update)
- 如果当前值
==
预期值,则以原子方式将该值设置为给定的更新值。可能意外失败并且不提供排序保证,因此几乎只是
compareAndSet
的适当替代方法。 -
-
- 参数:
expect
- 预期值update
- 新值- 返回:
- 如果成功,则返回 true。
set
public final void set(boolean newValue)
- 无条件地设置为给定值。
-
-
- 参数:
newValue
- 新值
lazySet
public final void lazySet(boolean newValue)
- 最终设置为给定值。
-
-
- 参数:
newValue
- 新值- 从以下版本开始:
- 1.6
getAndSet
public final boolean getAndSet(boolean newValue)
- 以原子方式设置为给定值,并返回以前的值。
-
-
- 参数:
newValue
- 新值- 返回:
- 以前的值
toString
public String toString()