老师布置作业,模拟卖票。
[Java] 纯文本查看 复制代码 /*java多线程模拟实现12306售票
业务描述
假设有200张票,用4个线程去订票,不能有两个或者以上的线程订到了
同一个票(原因就不说了),当最后一张票卖掉的时候结束,再订就抛
异常提示出票卖完了。
业务分析,要实现以上功能,
1、需要创建一个车票类,初始化票,卖票的接口saleTicket()
2、自定义异常的一个类。
3、创建卖票线程类,在run方法中卖车票。
4、初始化车票的线程,负责初始化车票,也就是初始化Ticket类中的数组。
5、创建主方法进行测试。*/
public class Test {
public static void main(String[] args) {
Ticket ticket=new Ticket();
Thread thread=new Thread(new InitializationTicketThread(ticket));
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread thread1=new Thread(new SaleTicketThread(ticket));
Thread thread2=new Thread(new SaleTicketThread(ticket));
Thread thread3=new Thread(new SaleTicketThread(ticket));
Thread thread4=new Thread(new SaleTicketThread(ticket));
thread1.setName("1号售票窗口");
thread2.setName("2号售票窗口");
thread3.setName("3号售票窗口");
thread4.setName("4号售票窗口");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
interface SaleTicket{
String saleTicket()throws SaleTicketException;
}
class Ticket implements SaleTicket{
private String[] tickets=new String[200];
private int index=0;
public Ticket() {
}
public Ticket(String[] tickets, int index) {
this.tickets = tickets;
this.index = index;
}
public String[] getTickets() {
return tickets;
}
public void setTickets(String[] tickets) {
this.tickets = tickets;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public void initializationTicket(){
for (int i=0;i<tickets.length;i++){
tickets[i]=i+1+"号车票";
}
}
public synchronized String saleTicket() throws SaleTicketException {
if (index<tickets.length&&tickets[index]!=null){
String str=Thread.currentThread().getName()+"--->成功卖出"+tickets[index];
tickets[index++]=null;
return str;
}else {
throw new SaleTicketException("票已经卖完了,买票失败");
}
}
}
class SaleTicketThread implements Runnable{
private Ticket ticket;
public SaleTicketThread(Ticket ticket) {
this.ticket = ticket;
}
public void run() {
for (int i=0;i<60;i++){
try {
System.out.println(ticket.saleTicket());
} catch (SaleTicketException e) {
e.printStackTrace();
break;
}
}
}
}
class InitializationTicketThread implements Runnable{
private Ticket ticket;
public InitializationTicketThread(Ticket ticket) {
this.ticket = ticket;
}
public void run() {
ticket.initializationTicket();
}
}
class SaleTicketException extends Exception {
public SaleTicketException() {
}
public SaleTicketException(String message) {
super(message);
}
} |