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