public class SaleTicket implements Runnable{ private int total=100; private int getTotal(){ return total; } public void sellTicket(){ this.total--; } @Override public void run() { while(getTotal()>0){ synchronized (this) { if(getTotal()>0){ sellTicket(); System.out.println(Thread.currentThread().getName()+"卖了一张票:还剩"+getTotal()+"张票"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } if(getTotal()==0){ System.out.println("票已卖完"); } } } } } } public class SaleTicketTest { public static void main(String[] args) { SaleTicket st=new SaleTicket(); new Thread(st,"1号窗口").start();; new Thread(st,"2号窗口").start();; new Thread(st,"3号窗口").start();; new Thread(st,"4号窗口").start();; } }