使用try...finally...来保证释放锁unlock()一定会被执行。
public class SellTickets implements Runnable{ //共有100张票 private int tickets = 100; private Object obj = new Object(); private Lock lock = new ReentrantLock(); @Override public void run() { while (true) { try { lock.lock(); if (tickets > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票"); tickets--; } } finally { lock.unlock(); } } } } public class SellTicketsDemo { public static void main(String[] args) { SellTickets st = new SellTickets(); Thread t1 = new Thread(st,"窗口1"); Thread t2 = new Thread(st,"窗口2"); Thread t3 = new Thread(st,"窗口3"); t1.start(); t2.start(); t3.start(); } }
运行结果:
原文:https://www.cnblogs.com/pxy-1999/p/12804527.html