package cheshi1; /** * 卖票 * 有售票窗口 通过线程作为窗口 * 票数a:10 张票 * a>0 的时候可以卖票 * 卖过一张票需要a-- * 票售罄(卖完了) */ public class Test extends Thread{ /**票数**/ private static int a = 10; private static Object o = new Object(); public void run(){ //卖票逻辑 while (true){ synchronized (o){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } if (a>0) { System.out.println(Thread.currentThread().getName()+"卖出一张票,但是还有票,赶紧买吧,还有"+a+"张"); a--; }else { System.out.println("没票了,下次再来吧"); System.exit(0);//退出 } } } } public static void main(String[] args) { int i=1; while (i<3) { Test test = new Test(); test.setName("窗口一" + i); test.start(); i++; } } }
优化了一下售票系统
于 2022-07-21 10:06:54 首次发布