package com.net.exercise;
/**
* 售票小程序,通过多线程实现多窗口售票
*
* @author xunenz
*
*/
class TicketdBackstage {
private int TicketTotalCount = 100;
// 单例
private TicketdBackstage() {}
private static TicketdBackstage instance = new TicketdBackstage();
public static TicketdBackstage getInstance() {
return instance;
}
public void ticketd(String windowNum) throws Exception {
int numb = TicketTotalCount--;
if (numb > 0) {
System.out.println(windowNum + "号窗口出票Id:" + numb);
} else {
throw new Exception("票已经售完!"); // 当票的数量没有时,抛出异常
}
}
}
/**
* 销售票款
*/
public class SellTicket{
public static void main(String[] args) {
window("1", 2); // 参数可以修改
window("2", 1);
window("3", 1);
}
/**
* 启动售票窗口
*
* @param windowNum 窗口号
* @param memberNum 窗口能售出的票数
*/
private static void window(final String windowNum, final int memberNum) {
new Thread() {
@Override
public void run() {
TicketdBackstage tb = TicketdBackstage.getInstance();
for (int i = 0; i < memberNum; i++) {
try {
tb.ticketd(windowNum);
} catch (Exception e) {
System.out.println("" + e.getMessage());
return;
}
}
}
}.start();
}
}
售票小程序,通过多线程实现多窗口售票
最新推荐文章于 2021-02-28 00:15:40 发布