package com.leo;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 解决线程安全方式三:Lock锁
 * synchronized机制在执行完相应的同步代码以后,自动地释放同步监视器
 * Lock需要手动地同步,结束同步也需要手动
 */
class Window implements Runnable{
    private int ticket = 100;
    private ReentrantLock lock = new ReentrantLock(true);
    @Override
    public void run() {
        while(true) {
           try{
               // 上锁
               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 {
                // 解锁
               lock.unlock();
           }
        }
    }
}
public class LockTest {
    public static void main(String[] args) {
        Window window = new Window();
        Thread thread1 = new Thread(window);
        Thread thread2 = new Thread(window);
        Thread thread3 = new Thread(window);

        thread1.setName("窗口1");
        thread2.setName("窗口2");
        thread3.setName("窗口3");

        thread1.start();
        thread2.start();
        thread3.start();
    }
}