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