这篇文章主要介绍Java多线程如何实现模拟12306火车站售票系统,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!该系统一共涉及到3个类:车票(Ticket)12306系统(System12306)售票窗口(Windo
这篇文章主要介绍Java多线程如何实现模拟12306火车站售票系统,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
该系统一共涉及到3个类:
车票(Ticket)
12306系统(System12306)
售票窗口(Window)
车票类,涉及三个属性:
起始站
终点站
票价
public class Ticket { //起始站 private String startStation; //终点站 private String destination; //票价 private Float price; public Ticket(){} public Ticket(String startStation, String destination, Float price) { this.startStation = startStation; this.destination = destination; this.price = price; } //为了让打印输出时方便,我们重写toString方法 public String toString() { StringBuilder builder = new StringBuilder("["); builder.append(this.startStation); builder.append("--->"); builder.append(this.destination); builder.append(":"); builder.append(this.price); builder.append("]"); return builder.toString(); } //get() and set()....}
12306系统,有一个属性—>Vector集合,有一个方法—>获取一张车票getTicket()
public class System12306 { //设计一个单例模式 private System12306(){} private static volatile System12306 sys; public static System12306 getInstance(){ if (sys == null){ synchronized (System12306.class){ if(sys == null) sys = new System12306(); } } return sys; } //属性,用一个集合存票,我们使用线程安全的Vector,或者使用Stack,它继承了Vector private Vector<Ticket> tickets = new Vector<>(); private String[] starts = {"北京","天津","太原","运城","西安"}; private String[] ends = {"上海","武汉","苏州","深圳","昆明","广州"}; //当前系统创建后,就给tickets集合赋值 { for(int i = 10;i<100;i++){//一共90张票 int r1 = (int)(Math.random()*starts.length); int r2 = (int)(Math.random()*ends.length); float price = r1*r2*5+140; tickets.add(new Ticket(starts[r1],ends[r2],price)); } } //设计一个方法,从集合中获取一张票 public Ticket getTicket(){ try { return tickets.remove(0); }catch (Exception e){ return null; } }}
售票窗口类,有一个属性—>窗口名称,有一个方法—>出售车票sellTicket()
同一时间有多个窗口同时售票,该类实现了Runnable接口,达到多线程并发的效果
public class Window implements Runnable { private String windowName;//窗口的名字 public Window(String windowName){ this.windowName = windowName; } @Override public void run() { this.sellTicket(); } public void sellTicket(){ while (true){ System12306 sys = System12306.getInstance(); Ticket ticket = sys.getTicket(); if(ticket==null){ System.out.println("对不起,"+windowName+"窗口车票已售完..."); break; } System.out.println("从"+windowName+"窗口售出:"+ticket); } }}
测试代码:
public class TestMain { public static void main(String[] args) { Window win1 = new Window("北京西站"); Window win2 = new Window("运城北站"); Window win3 = new Window("太原南站"); new Thread(win1).start(); new Thread(win2).start(); new Thread(win3).start(); }}
多线程并发执行的效果:
以上是“Java多线程如何实现模拟12306火车站售票系统”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注编程网精选频道!
--结束END--
本文标题: Java多线程如何实现模拟12306火车站售票系统
本文链接: https://lsjlt.com/news/278130.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0