1 ImportJava.util.concurrent.locks.Lock;2 ImportJava.util.concurrent.locks.ReentrantLock;3 4 5 /**6 * Thread lock technology for JAVA57 * Lock is more object-oriented than the synchronized in the traditional threading model, similar to the lock in life. 8 * The lock itself should also be an object. Two threads executing code fragments to achieve the effect of a synchronous mutex, they must be9 * used in the same lock object. A lock is an internal method on the class that represents the resource to be manipulated, not in the thread code. Ten * @authorlitaiqing One */ A Public classLocktest { - - Public Static voidMain (string[] args) { the Newlocktest (). Init (); - } - - Private voidinit () { + /** - * Internal classes access local variables, local variables must be final + * If this code is in main error, because static code block can not access the inner class A */ at FinalOutputer Outputer =NewOutputer (); - NewThread (NewRunnable () { - @Override - Public voidrun () { - while(true){ -Outputer.output ("Zhangxiaoxiang"); in } - } to }). Start (); + NewThread (NewRunnable () { - @Override the Public voidrun () { * while(true){ $Outputer.output ("Lihuoming");Panax Notoginseng } - } the }). Start (); + } A the Static classoutputer{ +Lock lock =NewReentrantlock (); - Public voidoutput (String name) { $ intLen =name.length (); $ Lock.lock (); - Try{ - for(inti = 0; i < Len; i++){ the System.out.print (Name.charat (i)); - }Wuyi System.out.println (); the}finally{ - Lock.unlock (); Wu } - } About } $}
Thread Lock Technology for 11.JAVA5