用Lock ReentrantLock 对象实现售票机制


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

/**
 * 用Lock对象实现售票机制
 */
public class SellTicketDemo {

    public static void main(String[] args) {

        // 创建资源对象
        SellTicket sellTicket = new SellTicket();

          // 创建窗口
        Thread threadA = new Thread(sellTicket, "窗口 A");
        Thread threadB = new Thread(sellTicket, "窗口 B");
        Thread threadC = new Thread(sellTicket, "窗口 C");

         // 开启线程
        threadA.start();
        threadB.start();
        threadC.start();
    }
}


// 售票机
class SellTicket implements Runnable {

    private int ticketNum = 100;

    private Lock lock = new ReentrantLock();

    // 进货
    public void run() {
        while (ticketNum > 0) {
            try {
                lock.lock();

                if (ticketNum > 0) {
                    try {
                        TimeUnit.MILLISECONDS.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " 正在出售第  " + (ticketNum--));
                }
            } finally {
                // 释放锁
                lock.unlock();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/xiaojin21cen/article/details/81783698
今日推荐