现在,让我们从原子布尔开始说。 自己也正好复习。 官方说明如下
可以用原子更新的布尔值。 有关原子变量属性的说明,请参见java.util.concurrent.atomic
包的规格。 原子布尔可用于APP应用程序,如原子更新的标志,但不能用于替换布尔。
换言之,Atomic是原子意义上的,在高并发性的情况下,可以保证只有一个线程可以访问该属性值。 (类似于我们之前说的volatile )
一般来说,AtomicBoolean可以有效地同时处理“只初始化一次”功能要求。
私有身份证明初始化=newatomicbooleaninitialized (false; public void init () if(initialized.compareandset ) false,true ) /将初始化代码放在此处…)如果没有AtomicBoolean,则使用volatile
publicstaticvolatileinitialized=false; 公共void init () if(initialized==false ) ) { initialized=true; //在这里初始化代码……}太不可思议了,让我们看看原子布尔的源代码吧。 查看源代码如下所示。
publicclassatomicbooleanimplementsjava.io.serializable { privatestaticfinallongserialversionuid=4654671469456979 l; //setuptouseunsafe.compareandswapintforupdatesprivatestaticfinalunsafeunsafe=unsafe.get unsafe (专用测试功能登录) static { try } value offset=unsafe.objectfieldoffset (atomic boolean.class.getdeclaredfield (' value ' ) ); }catch(exceptionex ) thrownewerror ) ex; } }私有电压int value;/* * creates anew { @ codeatomicboolean } withthegiveninitialvalue.* * @ paraminitialvaluetheinitialvalue */public atomic1333 }/* * * creates anew { @ codeatomicboolean } with initial value { @ code false }.*/publicatomicboolean { }/* retur rean @=0; }/* * * atomicallysetsthevaluetothegivenupdatedvalue * ifthecurrentvalue { @ code==} theexpectedvalue.* * @ paramexpected @ return { @ code true } if successful.falsereturnindicatesthat * theactualvaluewasnotequaltotheexpectedvalue.*/publicted int u=update? 1 : 0; return unsafe.compareandswapint (this,valueOffset,e,u ); }/* * * atomicallysetsthevaluetothegivenupdatedvalue * ifthecurrentvalue { @ code==} theexpectedvalue.* * pa href=' papa spuriouslyanddoesnotprovideorderingguarantees/a, sois * onlyrarelyanappropriatealternativeto { @ codecompareandset }.* * @ paramexpecttheexpectedvalue * @ paramupdatetethenewvalue publicbooleanweakcompareandset (布尔表达式,布尔更新) { int e=expect? 1 : 0; int u=update? 1 : 0; return unsafe.compareandswapint (this,valueOffset,e,u ); }/* * * unconditionallysetstothegivenvalue.* * @ paramnewvaluethenewvalue */publicfinalvoidset (布尔新值) ) vallue }/* * * eventuallysetstothegivenvalue.* * @ paramnewvaluethenewvalue * @ since 1.6 */publicfinalvoidlazyset (布尔新vew unsafe.putorderedint(this,valueOffset,v ); }/* * * atomicallysetstothegivenvalueandreturnsthepreviousvalue.* * @ paramnewvaluethenewvalue * @ returnthepreviousvalue pvalue pvalue do { prev=get (; } while (! 比较性(prev,newValue ); 返回预览; }/* * * returnsthestringrepresentationofthecurrentvalue.* @ returnthestringrepresentationofthecurrentvalue */public strint
Java6以后出现的很多原子行的类,除了上面提到的原子布尔之外,原子布尔家族更强大。 稍后有时间介绍。 包括以下内容:
基类:
自动积分器、自动长、自动布尔;
参考类型:
atomic参考、atomic参考的ABA实例、AtomicStampedRerence、AtomicMarkableReference;
数组类型:
AtomicIntegerArray、AtomicLongArray、AtomicReferenceArray
原子修改器(Updater ) :
AtomicIntegerFieldUpdater、AtomicLongFieldUpdater、AtomicReferenceFieldUpdater
原文地址: https://www.Jian Shu.com/p/8 a 44 d 4a 819 BC