ReentrantLock锁


    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            lock.lock();
            sell();
            lock.unlock();
        }
    }

    private void sell() {
        if (ticketNum > 0) {
            System.out.println(Thread.currentThread().getName() + ":卖票" + ticketNum);
            ticketNum--;
        }
    }

你可能感兴趣的:(ReentrantLock锁)