5.7日答案:张林敏同学提供
package cn.itcast.exercise1;
import java.util.ArrayList;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
TicketSealCenter tCenter = TicketSealCenter.newInstance();
//生成3个售票窗口
SealWindow sWindow1=new SealWindow(tCenter);
SealWindow sWindow2=new SealWindow(tCenter);
SealWindow sWindow3=new SealWindow(tCenter);
try {
//售票窗口开始卖票
sWindow1.start();
sWindow2.start();
sWindow3.start();
//进行售票10秒钟
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
//售票窗口停止售票
sWindow1.stop();
sWindow2.stop();
sWindow3.stop();
}
}
}
class SealWindow extends Thread {
private TicketSealCenter ticketSealCenter;
public SealWindow(TicketSealCenter ticketSealCenter) {
super();
this.ticketSealCenter = ticketSealCenter;
}
@Override
public void run() {
System.out.println("售票大厅:"+this.getName()+" 已开始卖票.");
while (true) {
//模拟生成用户需要购买的票的id
int id = (int) (Math.random()*10 % 3);
//获取当前售票大厅所售票的信息
ArrayList<Ticket1> tickets = ticketSealCenter.getTickets();
for (Ticket1 ticket : tickets) {
//判断是否有票
if (ticket.getId() == id) {
//判断当前这种票是否还有票卖
if (ticket.getQuantity()>0) {
ticket.setQuantity(ticket.getQuantity()-1);
System.out.println("售票大厅:"+this.getName()+" 已售出票:"+ticket.getName()+" 还剩张数:"+ticket.getQuantity());
}else {
System.out.println(ticket.getName()+"已经没有票买了...");
}
break;
}//END If
}//END For
try {
//没卖一张票的时间
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Ticket1 {
//属性
private int id=0;
private String name;
private int quantity;
//统计当前类生成多少个对象
private static int count=0;
//实体类的构造函数
public Ticket1(String name, int quantity) {
super();
id = count++;
this.name = name;
this.quantity = quantity;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
class TicketSealCenter {
//存放票
private ArrayList<Ticket1> tickets = null;
private static TicketSealCenter ticketSealCenter = null;
public ArrayList<Ticket1> getTickets() {
return tickets;
}
//构造函数、生成票
public TicketSealCenter() {
tickets = new ArrayList<Ticket1>();
tickets.add(new Ticket1("[北京 -> 上海]",30));
tickets.add(new Ticket1("[北京 -> 香港]",30));
tickets.add(new Ticket1("[北京 -> 台湾]",30));
}
//生成一个统一的售票大厅
public static TicketSealCenter newInstance(){
if (ticketSealCenter == null) {
ticketSealCenter = new TicketSealCenter();
}
return ticketSealCenter;
}
} |