赞
踩
/**java多线程模拟实现12306售票 业务描述 假设有200张票,用4个线程去订票,不能有两个或者以上的线程订到了 同一个票(原因就不说了),当最后一张票卖掉的时候结束,再订就抛 异常提示出票卖完了。 业务分析,要实现以上功能, 1、需要创建一个车票类,初始化票,卖票的接口saleTicket() 2、自定义异常的一个类。 3、创建卖票线程类,在run方法中卖车票。 4、初始化车票的线程,负责初始化车票,也就是初始化Ticket类中的数组。 5、创建主方法进行测试。*/
//票类
public class Ticket { Ticket[] tickets=new Ticket[200]; int no; String name; double fares; //索引判断是否卖完票 int index=200; public Ticket() { } public Ticket(int no, String name, double fares) { this.no = no; this.name = name; this.fares = fares; } //卖票 public synchronized void saleTicket() { // TicketT t= new TicketT(); for (int i = 0; i < 60; i++) { if (index < 1) { System.out.println("票已售完"); return; } else { index--; System.out.println(Thread.currentThread().getName() + "已预定" + tickets[index].toString() + "剩余票数" + index); } } } //重写toString方法 @Override public String toString() { return "车票[" + "车次:" + no + ",行程:" + name + '\'' + ", 票价:" + fares + ']'; } }
package day33test; //线程类 public class TicketThread extends Thread{ private Ticket ticket; public TicketThread(Ticket ticket){ this.ticket=ticket; } @Override public void run() { ticket.saleTicket(); } } //初始化票 class TicketT extends Thread { Ticket ticket; public TicketT(){} public TicketT(Ticket ticket){ this.ticket=ticket; } @Override public void run() { for (int i = 0; i < ticket.tickets.length; i++) { if (i < 50) { ticket.tickets[i] = new Ticket(1001, "北京--->南宁", 140.00); } else if (i < 100) { ticket.tickets[i] = new Ticket(2001, "南宁--->北京", 140.00); } else if (i < 150) { ticket.tickets[i] = new Ticket(3001, "昆明--->南宁", 100.00); } else { ticket.tickets[i] = new Ticket(4001, "南宁--->昆明", 100.00); } } } }
package day33test; //测试类 public class TicketTest { public static void main(String[] args) { Ticket ticket=new Ticket(); TicketT begin=new TicketT(ticket); // Thread t1= new TicketThread(ticket); Thread t2= new TicketThread(ticket); Thread t3= new TicketThread(ticket); Thread t4= new TicketThread(ticket); begin.start(); //合并线程保证初始化先进行 try { begin.join(); } catch (InterruptedException e) { e.printStackTrace(); } TicketT tis=new TicketT(); t1.setName("一号窗口"); t2.setName("二号窗口"); t3.setName("三号窗口"); t4.setName("四号窗口"); t1.start(); t2.start(); t3.start(); t4.start(); //测试初始化是否完成 /* for (int i = 0; i <begin.ticket.tickets.length ; i++) { System.out.println(begin.ticket.tickets[i]); } */ } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。