首页 > 编程知识 正文

megalign同源序列分析教程,多线程atomicboolean

时间:2023-05-05 04:42:24 阅读:146381 作者:1679

仔细查看AtomicBoolean源代码AtomicBoolean,可以为原子读写布尔变量提供解决方案。 此类通常用于原子更新状态识别位,如flag。

类定义publicclassatomicbooleanimplementsjava.io.serializable { } atomic boolean的类定义很简单,提供了序列化接口。

属性定义privatestaticfinallongserialversionuid=465467146979456979 l; privatestaticfinalunsafeunsafe=unsafe.get unsafe (; 私密性统计信息长期演进; 私有电压输入值; 前面的三个属性在原子类的属性中,所以省略说明。

value属性的值为0和1,0表示false,1表示true。

静态属性初始化static { try } value offset=unsafe.objectfieldoffset (atomic boolean.class.getdeclaredfield (' value ' ) ); }catch(exceptionex ) thrownewerror ) ex; }构造函数publicatomicboolean { } publicatomicboolean (布尔初始化值) { value=初始化值? 1 : 0; }如构造函数所示,AtomicBoolean在内部用0和1表示true和false。

get和set方法公共最终布尔get () { return value!=0; } publicfinalvoidset (布尔新值) { value=newValue? 1 : 0; } toString方法公共字符串} toString () returnboolean.tostring(get ) ); } lazySet方法publicfinalvoidlazyset (布尔新值) { int v=新值? 1 : 0; unsafe.putorderedint(this,valueOffset,v ); } compareAndSet方法publicfinalbooleancompareandset (布尔表达式,布尔更新) { int e=expect? 1 : 0; int u=update? 1 : 0; return unsafe.compareandswapint (this,valueOffset,e,u ); } publicbooleanweakcompareandset (布尔表达式,布尔更新) { int e=expect? 1 : 0; int u=update? 1 : 0; return unsafe.compareandswapint (this,valueOffset,e,u ); 如果expect的值与AtomicBoolean的当前值相同,则将AtomicBoolean的值设置为update并返回true。 否则,返回false而不更新。 compareAndSet和weakCompareAndSet没有区别。

getandsetpublicfinalbooleangetandset (布尔新值) {布尔预览; do{ prev=get (; }while (! 比较性(prev,newValue ); 返回预览; } getAndSet方法将AtomicBoolean的值设置为newValue,并返回预设置值。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。