** * *@ Description: Lock is more object-oriented than the traditional threading model of synchronized, similar to the lock in life, the lock itself should be an object, two threads executing code fragments to achieve the effect of synchronous interoperability*They must use the same lock, which is on-line to represent the internal method of the resource's inner class to be manipulated, rather than the thread's method.*@ Author: wnj.*@ Created: May 16, 2017.* @ Version: 1.0 . */ Public classLocktest {/** * @paramargs*/ Public Static voidMain (string[] args) {Newlocktest (). Init (); } Private voidinit () {FinalOutputer Outputer =NewOutputer (); //A NewThread (NewRunnable () {@Override Public voidrun () { while(true) { Try{Thread.Sleep (10); } Catch(interruptedexception e) {e.printstacktrace (); } //If a thread has not finished printing, the B thread is scheduled to execute, then the print is incompleteOutputer.output ("Zhangxiaoxiang"); }}). Start (); //B NewThread (NewRunnable () {@Override Public voidrun () { while(true) { Try{Thread.Sleep (10); } Catch(interruptedexception e) {e.printstacktrace (); } outputer.output ("Lihuoming"); }}). Start (); } /*** @ Description: The lock is on-line represents the internal method of the inner class of the resource to be manipulated * @ Author: wnj. * @ creation Time: May 16, 2017. * @ Version: 1.0. */ Static classOutputer {lock lock=NewReentrantlock (); /*** Use lock * < feature description > *@paramname*/ Public voidoutput (String name) {intLen =name.length (); Lock.lock (); Try { for(inti = 0; i < Len; i++) {System.out.print (Name.charat (i)); } System.out.println (); } finally{lock.unlock (); } } /*** Use synchronized * < function description > *@paramname*/ Public synchronized voidoutput2 (String name) {intLen =name.length (); for(inti = 0; i < Len; i++) {System.out.print (Name.charat (i)); } System.out.println (); } /*** Use synchronized * < function description > *@paramname*/ Public Static synchronized voidoutput3 (String name) {intLen =name.length (); for(inti = 0; i < Len; i++) {System.out.print (Name.charat (i)); } System.out.println (); } }}
and the contract Java.util.concurrent.locks.Lock