public class SaleWindows {
public static void main(String[] args){
SaleCenter sc = new SaleCenter(200);
SaleTicket st = new SaleTicket();
sc.setNum(st);// 售票中心分配票数
// 创建线程
Thread t1 = new Thread(st,"一号窗口");
Thread t2 = new Thread(st,"二号窗口");
Thread t3 = new Thread(st,"三号窗口");
Thread t4 = new Thread(st,"四号窗口");
// 启动线程
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class SaleTicket implements Runnable{
private int tickets;
public void setTotalNum(int tickets){
this.tickets = tickets;// 设置发售总票数
}
private synchronized void sale(){
if(tickets > 0){
System.out.println(Thread.currentThread().getName() + "售出第 "+ (tickets--)+"张票");
try{
Thread.sleep(tickets);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public void run(){
while(tickets > 0){
sale();
}
}
}
class SaleCenter{
private int ticketsnum;
SaleCenter(int ticketsnum){
this.ticketsnum = ticketsnum;
}
public void setNum(SaleTicket st)
{
st.setTotalNum(ticketsnum); // 授权票数上限
}
} |