Overview and use of lock lock after Android (Java) Learning Note 69:jdk5

Source: Internet
Author: User

1  Packagecn.itcast_01;2 3 ImportJava.util.concurrent.locks.Lock;4 ImportJava.util.concurrent.locks.ReentrantLock;5 6  Public classSellticketImplementsRunnable {7 8     //Define Tickets9     Private intTickets = 100;Ten  One     //Defining Lock Objects A     PrivateLock lock =NewReentrantlock (); -  - @Override the      Public voidrun () { -          while(true{//use try{}finally{} here because of the worry that the program locks up after the problem, can not jump out of  unlock -             Try { -                 //Locking + Lock.lock (); -                 if(Tickets > 0) { +                     Try { AThread.Sleep (100); at}Catch(interruptedexception e) { - e.printstacktrace (); -                     } - System.out.println (Thread.CurrentThread (). GetName () -+ "Selling" + (tickets--) + "Ticket");
- } in}finally { - //Release Lock to Lock.unlock (); + } - } the } * $}
1  Packagecn.itcast_01;2 /*3 * Although we can understand the problem of locking objects for synchronous code blocks and synchronous methods, we do not directly see where the lock was added, where the lock was released,4 * In order to express more clearly how to lock and release the lock, JDK5 provides a new lock object after lock. 5  * 6 * Lock: (interface)7 * void Lock (): Gets the lock. 8 * void Unlock (): Release lock. 9 * Reentrantlock is the implementation class of lock. (Interface implementation Class)Ten  */ One  Public classSellticketdemo { A      Public Static voidMain (string[] args) { -         //Create a Resource object -Sellticket st =NewSellticket (); the  -         //Create a three window -Thread T1 =NewThread (St, "Window 1")); -Thread t2 =NewThread (St, "Window 2")); +Thread t3 =NewThread (St, "Window 3")); -  +         //Start Thread A T1.start (); at T2.start (); - T3.start (); -     } -}

Overview and use of lock lock after Android (Java) Learning Note 69:jdk5

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.