Lock use the interface to solve thread safety issues

cn.itcast.demo16.Demo09.Lock Package ; 

Import java.util.concurrent.locks.Lock ;
Import java.util.concurrent.locks.ReentrantLock ;

/ **
* @author newcityman
* @date 2019/7/24 - 20 is : 38
* solve thread safety issues third option: use lock lock
* java.util.concurrent.locks.lock Interface
* lock implementations provide more extensive locking available than using synchronized methods and statements operation
* lock interface method:
* void lock () Get lock
* void unlock () releases the lock
* java.util.concurrent.Locks.ReentrantLock implements lock Interface
*
* the procedures:
* 1, create a ReentrantLock implement lock interface occupant position
* 2, call lock lock the interface method may appear before the code security issues acquire lock
* 3, call unLock method releases the lock lock interface in the code after the security issues that may arise
*/
public class RunnableImpl implements java.lang.Runnable {
private int ticket = 100;

Lock l = new ReentrantLock();

@Override
public void run() {
while (true) {
l.lock();
try {
Thread.sleep(10);
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "--->正在卖" + ticket + "张票");
ticket--;
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
l.unlock();
}
}
}
}



package cn.itcast.demo16.Demo09.Lock;

/**
* @author newcityman
* @date 2019/7/24 - 20:44
*/
public class Demo01TicketLock {
public static void main(String[] args) {
RunnableImpl impl = new RunnableImpl();
Thread t1 = new Thread(impl);
Thread t2 = new Thread(impl);
Thread t3 = new Thread(impl);

t1.start();
t2.start();
t3.start();
}
}

Guess you like

Origin www.cnblogs.com/newcityboy/p/11240938.html