//车票类 public class Ticker { //车票应该有发出地、终点、票价等信息 private String start; private String end; private Float price; public Ticker(){} public Ticker(String start, String end, Float price) { this.start = start; this.end = end; this.price = price; } public String toString(){ StringBuilder stringBuilder = new StringBuilder("["); stringBuilder.append(this.start); stringBuilder.append("--->"); stringBuilder.append(this.end); stringBuilder.append(" : "); stringBuilder.append(this.price); stringBuilder.append("]"); return stringBuilder.toString(); } public String getStart() { return start; } public void setStart(String start) { this.start = start; } public String getEnd() { return end; } public void setEnd(String end) { this.end = end; } public Float getPrice() { return price; } public void setPrice(Float price) { this.price = price; } } import java.util.Vector; //火车站类 public class TrainStation { //火车站内有多个窗口,同时开始售票 //此类需要产生很多很多的票使多个窗口开始售票。 //但是火车站只有一个,不能NEW多个,所以需要一个单例模式 private static TrainStation trainStation = new TrainStation(); private TrainStation(){} public static TrainStation getTrainStation(){ return trainStation; } //票是在类加载时就需要产生的,所以需要用程序块,并且将票存储在集合内 //集合便于更改,所以不用数组存放 //Vector集合线程安全,且不会产生重复的 内容, private Vector<Ticker> vector = new Vector<Ticker>(); { for(int i=1;i<=100;i++){ vector.add(new Ticker("西安站"+i+"座次","北京站",(i%5+5)*30F)); } } //需要一个方法,用来给窗口票 //返回类型是Ticker类型的 public Ticker getTicket(){ //每给一张票,票就少一张 try { return vector.remove(0); }catch (Exception e){ //如果捕捉到异常,则说明票已经售完了 return null; } } } //售票窗口类 public class Window extends Thread{ //多个窗口需要同时开启,同时售票 private String name; public Window(){} public Window(String name){ this.name = name; } //所以需要在此类中设置Run方法 //窗口都要售票,需要有一个售票方法 public void sellTicket(){ while (true){ TrainStation trainStation = TrainStation.getTrainStation(); Ticker ticket = trainStation.getTicket(); if(ticket==null){ System.out.println(this.name+"窗口票已售完!"); break; } //重写toString方法,打印对象 System.out.println("从"+name+"售出:"+ticket); } } public void run(){ sellTicket(); } } public class Main { public static void main(String[] args){ Window window1 = new Window("西安站1号窗口"); Window window2 = new Window("西安站2号窗口"); Window window3 = new Window("西安站3号窗口"); Window window4 = new Window("西安站4号窗口"); window1.start(); window2.start(); window3.start(); window4.start(); } }