/**
* 票务类,单例实例
*/
public class Ticket implements Runnable {
private static Ticket sTicket;
/**
* 售票线程列表
*/
private List<Thread> mThreads;
/**
* 窗口数量
*/
private int mWindowNumber;
/**
* 预售数
*/
private int mTicketNumber;
/**
* 余票
*/
private int mResidueNumber;
/**
* 是否售完
*/
private boolean isSaleOff = false;
private List<String> mWindowNames = new ArrayList<String> ();
/**
* 私有化单例构造,预售票数和窗口数量
* @param ticket
* @param window
*/
private Ticket(int ticket, int window) {
initWindowNames();
this.mTicketNumber = ticket;
this.mResidueNumber = ticket;
this.mWindowNumber = window;
mThreads = new ArrayList<Thread> ();
if(mWindowNumber > 0 && mWindowNumber <= 8) {
for(int i = 0;i < mWindowNumber;i++) {
mThreads.add(new Thread(this, mWindowNames.get(i)));
}
} else {
mWindowNumber = 8;
}
}
/**
* 预设8个窗口
*/
private void initWindowNames() {
mWindowNames.add("学生窗口");
mWindowNames.add("普通窗口1");
mWindowNames.add("军人窗口");
mWindowNames.add("普通窗口2");
mWindowNames.add("老人窗口");
mWindowNames.add("普通窗口3");
mWindowNames.add("普通窗口4");
mWindowNames.add("普通窗口5");
}
/**
* 获取票务实例
* @param ticket 预售票数
* @param window 窗口数
* @return
*/
public static Ticket getTicketInstance(int ticket, int window) {
if(sTicket == null) {
sTicket = new Ticket(ticket, window);
}
return sTicket;
}
/**
* 开始售票
*/
public void start() {
for(int i=0;i<mWindowNumber;i++) {
mThreads.get(i).start();
}
}
/**
* 售票
*/
private synchronized void saleTicket() {
if(!isSaleOff) {
//有票,开卖
System.out.println("------------ 欢迎选择: " + Thread.currentThread().getName() + " ------------");
System.out.println("第 " + mResidueNumber +" 张票");
mResidueNumber--;
System.out.println("剩余票数:" + mResidueNumber + " 张");
System.out.println("--------------------------------------");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
//售完
System.out.println("亲,来晚了,没票了...");
}
}
public void run() {
while(!isSaleOff) {
if(mResidueNumber>0 && mResidueNumber<=mTicketNumber) {
//大于0,小于预售数量
saleTicket();
} else {
isSaleOff = true;//无票
}
}
}
}
public class MainClass {
public static void main(String[] args) {
Ticket ticket = Ticket.getTicketInstance(100, 3);//100张票,3个窗口
ticket.start();
}
}
|