多线程售票
package threadT; public class ThreadMain { public static void main(String args[]) { SellTicket str = new SellTicket(10); Thread tr1 = new Thread(str, "窗口1"); Thread tr2 = new Thread(str, "窗口2"); Thread tr3 = new Thread(str, "窗口3"); tr1.start(); tr2.start(); tr3.start(); } }
package threadT; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class SellTicket implements Runnable { // 定义票的数量 private int tickets = 0; public SellTicket(int count) { tickets = count; } // 定义锁对象 private final Lock lock = new ReentrantLock(); public void run() { // 卖完标记 boolean over = false; while (true) { try { if (tickets == 0) { System.out.println(Thread.currentThread().getName() + "检测到已售完"); over = true; break; } // 加锁 lock.lock(); if (tickets > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "正在出售第" + (tickets--) + "张票"); } } finally { if (!over) // 释放锁 lock.unlock(); } } } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步