Package lock ; / * Three ways: Lock Lock different synchronized and the lock 1.sychronized after completion of execution of code blocks belonging to the respective synchronization monitor automatically released, need to manually start the synchronization lock preferred whenever lock -> block synchronization method -> Synchronization Method (outside the method body) to achieve Runnable object has been called three threads, and then run the object method's contribution to the operation of the resource lock is locked up @author zsben @Create 2020-01-03 23:55 * / Import the Java. util.concurrent.locks.ReentrantLock; class the Window the implements the Runnable { Private int Ticket = 100 ; // 1. examples of lock Private of ReentrantLock lock = new new of ReentrantLock ( to true ); // fair = to true: fair lock, the thread take turns @Override public void run() { while(true){ try{ //2.调用lock方法 lock.lock(); if(ticket>0){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+": "+ticket); ticket--; }else break; } finally { //3.调用解锁方法 lock.unlock(); } } } } public class LockTest { public static void main(String[] args) { Window w = new Window(); Thread t1 = new Thread(w); Thread t2 = new Thread(w); Thread t3 = new Thread(w); t1.start(); t2.start(); t3.start(); } }
java-based synchronization lock --lock
Guess you like
Origin www.cnblogs.com/zsben991126/p/12148326.html
Ranking