资源描述:
《java中synchronized的用法详解(the usage of java in synchronized)》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、java中synchronized的用法详解(TheusageofJavainsynchronized)TheusageofJavainsynchronizedThekeywordoftheJavalanguage,whenitisusedtomodifyamethodorablockofcode,canguaranteethatatthesametimeatmostonlyonethreadexecutesthecode.First,whentwoconcurrentthreadsaccessthesynchronized(this)synchroniz
2、ationblockinthesameobjectobject,onlyonethreadcanbeexecutedatatime.Anotherthreadmustwaitforthecurrentthreadtoexecutethecodeblockbeforeexecutingthecodeblock.Two,however,whenathreadaccessesasynchronized(this)synchronizationblockofobject,anotherthreadcanstillaccessthenonsynchronized(t
3、his)synchronizationcodeblockintheobject.Threeand,inparticular,whenathreadaccessesasynchronized(this)synchronizationblockofobject,otherthreadswillblockaccesstoallothersynchronized(this)synchronouscodeblocksinobject.Thefourandthirdexamplesarealsoapplicabletoothersynchronouscodeblock
4、s.Thatis,whenathreadaccessesasynchronized(this)synchronizationblockofobject,itgetstheobjectlockoftheobject.Asaresult,otherthreadstemporarilyblockaccesstoallsynchronouscodepartsoftheobjectobject.Five.TheaboverulesarealsoapplicabletootherobjectlocksIllustrate:First,whentwoconcurrent
5、threadsaccessthesynchronized(this)synchronizationblockinthesameobjectobject,onlyonethreadcanbeexecutedatatime.Anotherthreadmustwaitforthecurrentthreadtoexecutethecodeblockbeforeexecutingthecodeblock.Packageths;Public,class,Thread1,implements,Runnable{Public,void,run(){Synchronized
6、(this){For(int,I=0,I,<5,i++){System.out.println(Thread.currentThread().GetName()+"synchronizedloop"+i;}}}Public,static,void,main(String[],args){Thread1T1=new,Thread1();Thread,Ta=new,Thread(T1,A);Thread,TB=new,Thread(T1,B);Ta.start();Tb.start();}}Result:Asynchronizedloop0Asynchroni
7、zedloop1Asynchronizedloop2Asynchronizedloop3Asynchronizedloop4Bsynchronizedloop0Bsynchronizedloop1Bsynchronizedloop2Bsynchronizedloop3Bsynchronizedloop4Two,however,whenathreadaccessesasynchronized(this)synchronizationblockofobject,anotherthreadcanstillaccessthenonsynchronized(this
8、)synchronizationcodeblockintheobj