Java 22-14 JDK1.5 Lock locks

Source: Internet
Author: User

In the process of thread safety, Although we can understand the problem of locking object of synchronous code block and synchronous method,

But we did not see directly where the lock was added, where the lock was released,

In order to express more clearly how to lock and release the lock, JDK5 later provided a new lock objectlock.

Note: Lock is an interface.

2 Common Methods:
void lock (): Gets the Lock.
void unlock (): release lock.
Reentrantlock is the implementation class for LOCK.

1  public classSellticketImplements Runnable {//don't Forget this inheritance interface2     //Define 100 Tickets3     Private intTickets = 100;4 5     //Defining Lock Objects6     PrivateLock lock =NewReentrantlock ();7 8      public voidRun () {9 Ten          // The try with no catch is used Here. Finally in the format, the middle of the code has a problem, directly executes finally  one  a          while(true) { -             Try { -                  the                 //lock , lock before the wrong code, as before - Lock.lock (); -                  -                 if(tickets > 0) { +                                          -                     //Sleep 0.1 seconds +                     Try { aThread.Sleep (100); at}Catch(interruptedexception E) { -                         //TODO auto-generated Catch block - e.printstacktrace (); -                     } -  - System.out.println (thread.currentthread (). getName () in+ "selling" + (tickets--) + "ticket"); -                 } to}finally { +                 //unlock the middle code if there is an exception, unlock it, - Lock.unlock (); the             } *         } $     }Panax Notoginseng}

Java 22-14 JDK1.5 Lock locks

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.