/*
* 第7题:编写三各类Ticket、SealWindow、TicketSealCenter分别代表票信息、
* 售票窗口、售票中心。售票中心分配一定数量的票,
* 由若干个售票窗口进行出售,利用你所学的线程知识来模拟此售票过程。
*/
public class Test7 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
SealWindow myWindow = new SealWindow();
new Thread(myWindow,"1号窗口").start();
new Thread(myWindow,"2号窗口").start();
new Thread(myWindow,"3号窗口").start();
new Thread(myWindow,"4号窗口").start();
}
}
//票信息
class Ticket {
}
//售票窗口
class SealWindow implements Runnable{
TicketSealCenter tsc = null;
public SealWindow() {
tsc = TicketSealCenter.getInstance();
}
public void run() {
while(!(tsc.hasticket())) {
System.out.println(Thread.currentThread().getName()+"售出了"+tsc.getid()+"号票!");
if(tsc.hasticket())
System.out.println(Thread.currentThread().getName()+"票已售完");
}
}
}
//售票中心
class TicketSealCenter {
private static int sumticket = 100;
private static boolean flag = false;
private static TicketSealCenter tsc = new TicketSealCenter();
private TicketSealCenter(){}
public static TicketSealCenter getInstance() {
return tsc;
}
public static synchronized boolean hasticket() {
if(sumticket>0) {
//System.out.println(Thread.currentThread().getName()+"售出了"+sumticket+"号票!");
sumticket--;
}else
flag = true;
return flag;
}
public int getid() {
return sumticket+1;
}
}
|
|