题目:编写三各类Ticket、SealWindow、TicketSealCenter分别代表票信息、售票窗口、售票中心。售票中心分配一定数量的票,由若干个售票窗口进行出售,利用你所学的线程知识来模拟此售票过程。
写的有不对的地方请多指正
//主函数
public static void main(String[] args) {
TicketSealCenter tsc=new TicketSealCenter(Ticket.getInstant());
tsc.setTicketNum(1000);
new SealWindow("第一个窗口").start();
new SealWindow("第二个窗口").start();
new SealWindow("第三个窗口").start();
new SealWindow("第四个窗口").start();
}
//创建票的类,采用单例模式,张孝祥老师说过,谁拥有数据,谁就要提供操作数据的方法。
public class Ticket {
private int num=0;
private static Ticket ticket=null;
private Ticket(){}
//获取票对象的静态方法
public static Ticket getInstant(){
if (ticket==null){
synchronized (Ticket.class) {
if (ticket==null){
ticket=new Ticket();
return ticket;
}
}
}
return ticket;
}
//设置票有多少张
public void setNum(int num){
this.num=num;
}
//判断是否还有票
public Boolean isHave(){
if (num<1) {
return false;
}else{
return true;
}
}
//卖票的方法
public int sealTicket(){
return num--;
}
}
//售票中心类
public class TicketSealCenter {
private Ticket tk;
public TicketSealCenter(Ticket ticket){
this.tk=ticket;
}
//用来设置票的总张数
public void setTicketNum(int num){
tk.setNum(num);
}
}
//售票窗口
public class SealWindow extends Thread {
private Ticket tk=Ticket.getInstant();
private String name;
public SealWindow(String name){
super(name);
this.name=name;
}
public void run() {
while(tk.isHave()){
synchronized (tk) {
if(!tk.isHave()){
break;
}
int num=tk.sealTicket();
System.out.println(this.getName()+"---"+name+"售出"+num+"号票");
}
}
System.out.println(name+"票已售完");
}
}