package J20250730.demo10_lock;

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

/**
 * @author WanJl
 * @version 1.0
 * @title SellTicket
 * @description 同步方法
 * @create 2025/7/30
 */
public class SellTicket implements Runnable {
    //总共100张票
    private int tickets = 100;
    //创建可重入锁对象
    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        while (true) {
            try {
                //加锁
                lock.lock();
                if (tickets > 0) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //显示XX窗口成功售票
                    System.out.println(name + "售票1张，还剩" + --tickets + "张票");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //锁必须要释放
                lock.unlock();
            }
        }
    }


}
