Java多线程 4个窗口按顺序卖100票

97 阅读1分钟
    private int ticketCount =100;
    private Object object = new Object();
    @Override
    public void run() {
        while (ticketCount>0){
            synchronized (object){
                if (ticketCount>0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"正在出售第:"+(ticketCount--)+"张票!");
                }
            }
        }
    }
}


    public static void main(String[] args) throws CloneNotSupportedException {
        
        SellTickets sellTickets = new SellTickets();
        Thread thread1 = new Thread(sellTickets,"窗口1");
        Thread thread2 = new Thread(sellTickets,"窗口2");
        Thread thread3 = new Thread(sellTickets,"窗口3");
        Thread thread4 = new Thread(sellTickets,"窗口4");
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
    }
}

窗口1正在出售第:100张票!
窗口1正在出售第:99张票!
窗口1正在出售第:98张票!
窗口1正在出售第:97张票!
窗口1正在出售第:96张票!
窗口4正在出售第:95张票!
.
.
.
窗口2正在出售第:4张票!
窗口2正在出售第:3张票!
窗口2正在出售第:2张票!
窗口2正在出售第:1张票!