代码:
public class TicketReentLockDemo implements Runnable { private int ticketTotal = 100; private Lock lock = new ReentrantLock(); @Override public void run() { while (ticketTotal > 0) { try { lock.lock(); if (ticketTotal > 0) { try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "正在售出第 " + (ticketTotal--)); } } finally { lock.unlock(); } } } public static void main(String[] args) { TicketReentLockDemo ticketReentLockDemo = new TicketReentLockDemo(); Thread thread1 = new Thread(ticketReentLockDemo, "窗口1"); Thread thread2 = new Thread(ticketReentLockDemo, "窗口2"); Thread thread3 = new Thread(ticketReentLockDemo, "窗口3"); thread1.start(); thread2.start(); thread3.start(); } }
运行结果: