阳杰 发表于 2012-9-1 21:50
打错了几个字 不好意思,
//定义TicketSealCenter类
class TicketSealCenter
{
public static void main(String[] args)
{
// 生产 一千张高铁票 送到售票亭
Ticket t = new Ticket(1000);
//启动5个线程
SealWindow sw1 = new SealWindow("售票窗口一",t);
SealWindow sw2 = new SealWindow("售票窗口二",t);
SealWindow sw3 = new SealWindow("售票窗口三",t);
SealWindow sw4 = new SealWindow("售票窗口四",t);
SealWindow sw5 = new SealWindow("售票窗口五",t);
new Thread(sw1).start();
new Thread(sw2).start();
new Thread(sw3).start();
new Thread(sw4).start();
new Thread(sw5).start();
}
}
//定义SealWindow类
class SealWindow implements Runnable
{
//设置窗口属性
private String name;
private Ticket t;
public SealWindow(String name,Ticket t)
{
this.name = name;
this.t=t;
}
//覆盖run方法
public void run()
{
boolean b=true;
while(b)
{
synchronized(t)
{
//如果还有票,打印所售票的窗口和剩余的票数
if (t.sealTicket())
{
System.out.println(name+"·······售出一张,还剩余:"+t.getNum());
}
//如果没有,则打印“票已售完”
else
{
System.out.println("票已售完");
b=false;
}
}
}
}
}
//定义Tickt类
class Ticket
{
//设置属性所需售票数num
private int num;
public Ticket(int num)
{
this.num = num;
}
//返回剩余票数
public int getNum()
{
return num;
}
//功能:卖票,卖出去了返回 true,没卖出去返回false;
public boolean sealTicket()
{
if(num<=0)
{
return false;
}
else
{
num--;
return true;
}
}
}
运行结果如图,还是不对啊
|
|