线程安全方式03---Lock锁

/**
* 线程安全---Lock方式
*
* @Author: ITYW
* @Create 2020 - 10 - 26 - 19:16
*/
public class RunnableSecurity_Lock {
public static void main(String[] args) {
Runnable_Lock runnable_lock = new Runnable_Lock();
Thread t1 = new Thread(runnable_lock);
Thread t2 = new Thread(runnable_lock);
Thread t3 = new Thread(runnable_lock);

t1.setName("window01");
t2.setName("window02");
t3.setName("window03");

t1.start();
t2.start();
t3.start();
}
}
class Runnable_Lock implements Runnable{
private static int ticket = 100;
private ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try {
lock.lock();
if (ticket > 0){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"卖出了第"+ticket+"张");
ticket--;
}else {
break;
}
} finally {
lock.unlock();
}
}
}
}
原文地址:https://www.cnblogs.com/ITYW/p/13880547.html