资源描述:
《java同步机制(java同步机制)》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、java同步机制(java同步机制)JavaJssupportandsynchronizationmechanismformultithreadingislovedbyeveryone,anditseemsthatitiseasytosolvetheproblemofmultithreadsharingofdatasynchronizationusingthesynchronizedkeyword・Sowhat?Alsohavetosynchronizedkeywordroleindepthunderstanding,canbeconelusive・Ingeneral
2、,thesynchronizedkeywordcanbeusedasafunctionmodifierorasafunctionstatement,thatis,asynchronousmethodandasynchronousstatementblock.Forfurtherclassification,synchronizedcanworkoninstancevariables,object,reference(objectreferences),staticfunctions,andclassliterals(classnames,literalconstant
3、s).Beforeweelaborate,weneedtomakesomespecificpoints:A.regardlessofthesynchronizedkeywordaddedtothemethodorobject,thelockitobtainsistheobject,nottheobjectApieceofcodeorfunctionthatactsasalock一andthesynchronizationmethodislikelytobeaccessedbyotherthreadobjects.B.eachobjecthasonlyonelock(l
4、ock)associatedwithit.C.synchronizationiscostlyattheexpenseofthesystemandcanevencausedeadlocks,soavoidunnecessarysynchronization.Next,discusstheimpactofsynchronizedoncodegenerationindifferentplaces:SupposethatPlandP2aredifferentobjectsofthesameclass,inwhichthesynchronizationblocksorsynch
5、ronizationmethodsaredefined,andPlandP2cancallthem・1.whensynchronizedisusedasafunctionmodifier,thesamplecodeisasfollows:Public,synchronized,void,methodAAA()Thisisthesynchronizationmethod,sowhatobjectdoessynchronizedlockatthistime?Itlockstheobjectthatcallsthissynchronizationmethod.Thatist
6、osay,whenanobjectPlexecutesthissynchronizationmethodindifferentthreads,theyformmutualexclusionandachievesynchronization.However,anotherobjectP2generatedbytheClasstowhichtheobjectbelongsbelongstosynchronizedcanbecalledarbitrarily.Thesamplecodeaboveisequivalenttothefollowingcode:Public,vo
7、id,methodAAA()Synchronized(this)/(1)(1)whatdoes"this"mean?Itreferstotheobjectthatcallsthismethod,suchasPl.Itisobviousthatthesynchronizationmethodessentiallyappliessynchronizedtoobjectreference・-thegetthePlobjectlockthreadsynchronizationcancallthePlmethod,andforP2,thePllockandit