怎么给下面的多线程售票窗口改名为“售票窗口1”、“售票窗口2”、“售票窗口3”
class Test6
{
public static void main(String[] args)
{
Ticket ti=new Ticket();
SealWindow sw=new SealWindow(ti);
TicketSealCenter tsc=new TicketSealCenter(ti);
//开辟三个售票窗口,一个售票中心
Thread t1=new Thread(sw);
Thread t2=new Thread(sw);
Thread t3=new Thread(sw);
Thread t4=new Thread(tsc);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Ticket//资源
{
private int count=0;//记录生产的票数
private String name;
private boolean flag;
public synchronized void setTicket()
{
while(flag)
try
{
wait();
}
catch (Exception e)
{
}
count++;
System.out.println(Thread.currentThread().getName()+"--生产票--"+count);
flag=true;
notifyAll();
}
public synchronized void sealTicket()
{
while(!flag)
try
{
wait();
}
catch (Exception e)
{
}
Thread.currentThread().setName("售票中心");
System.out.println(Thread.currentThread().getName()+".....消费票....."+count);
//当消费出500张票时return,避免唤醒t1,t2,t3中等待的线程而继续执行setTicket()方法多生产一张票。
if(count==500)
return;
flag=false;
notifyAll();
}
}
class SealWindow implements Runnable//消费票
{
private Ticket ti;
SealWindow(Ticket ti)
{
this.ti=ti;
}
public void run()
{
for(int x=0;x<500;x++)
ti.setTicket();
}
}
class TicketSealCenter implements Runnable//生产票
{
private Ticket ti;
TicketSealCenter(Ticket ti)
{
this.ti=ti;
}
public void run()
{
for(int x=0;x<500;x++)
ti.sealTicket();
}
} |
|