Thread Lock Technology for 11.JAVA5

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.