package A_ShangGuiGu.Thread.ThreadTest;标签:同步,Thread,lock,ReentrantLock,lock1,线程,new From: https://www.cnblogs.com/zhazhawei906/p/16817807.html
import java.util.concurrent.locks.ReentrantLock;
/**
* 解决线程安全问题的方式三:Lock锁-----jdk5.0新增
* 1.首先要创建一个ReentrantLock的对象。
* 2.在操作同步数据之前上锁:lock1.lock();---例如在if语句之前
* 3.操作完数据后需要手动解锁-----lock1.unlock();
* 线程同步的优先级:Lock>同步代码块>同步方法---建议优先使用lock,比较灵活
*/
class Window implements Runnable{
private int chepiao = 100;
//1.实例化ReentrantLock对象。
ReentrantLock lock1 = new ReentrantLock();
@Override
public void run() {
while (true){
try {
//2.调用锁定方法lock
lock1.lock();
if (chepiao>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName()+"卖票,票号为:"+chepiao);
chepiao--;
}else {
break;
}
} finally {
//3.调用解锁方法unlock
lock1.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.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}