总共有100张票,模拟两个窗口来买票 package defaultpacage; import java.util.Random; public class TicketSeller extends Thread { public static Integer total=100; public static Integer getTotal() { return total; } public static void setTotal(Integer total) { TicketSeller.total = total; } public TicketSeller(String name){ super(name); } @Override public void run(){ while(TicketSeller.getTotal()>=0) { synchronized(TicketSeller.total) { int num=TicketSeller.getTotal(); System.out.println(this.getName()+"卖出票,还剩"+TicketSeller.getTotal()); TicketSeller.setTotal(num-1); } try { Thread.sleep(new Random().nextInt(1000)); } catch (Exception e) { // TODO: handle exception } } System.out.println("卖完了"); } public static void main(String args[]) { TicketSeller t1=new TicketSeller("t1"); TicketSeller t2=new TicketSeller("t2"); t1.start(); t2.start(); } }