环境:
IDEA——2019
jdk-9.0.4
源码如下:
Station 类
public class Station extends Thread{ public Station(String name) { super(name); } static int tick = 40; int tickets=0; // 创建一个静态钥匙 static Object ob = "aa"; @Override public void run() { while (tick > 0) { synchronized (ob) {// 锁 if (tick > 0) { tickets= (int) (Math.random()*10);//随机票数 if(tickets>tick) tickets=tick; tick=tick-tickets; System.out.println(getName() + "卖出了" + tickets + "张票"); System.out.println("还剩"+tick+"张"); } } try { sleep(1000);//休息 } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(getName()+"卖完啦"); } }MainC类(MainClass)
public class MainC { public static void main(String[] args) { Station station1=new Station("窗口1"); Station station2=new Station("窗口2"); Station station3=new Station("窗口3"); Station station4=new Station("窗口4"); Station station5=new Station("窗口5"); station1.start(); station2.start(); station3.start(); station4.start(); station5.start(); } }正常运行可得结果(^-^)V