//package Main;
**/**模拟简单车站购票系统问题(只考虑每个人购一张票)
* Instructions:
* 设:售票员持有两张五元零钱且票单价五元一张,先有
* 李先生持5元、杨先持10元、王先生持20前来购票,
* 且每个人都没有其他任何零钱的情况下的整个程序
* 线程同步调度和安全。
* @time:-2019/06/18
* @role(shei):-东方神祇(杨)
*/
public** class BuyticketMultithreadingDemo {
//public static void main(String[] args){}
}
//卖票
class sellTicket {
private int fiveYuan = 2;
private int tenYuan = 0;
private int twentyYuan = 0;
public synchronized void Sell(int money) {
if (money == 5) {
System.out.println("李先生您好!您给的是五元整,钱正好,找零(零元整)您买的票请收好。");
this.fiveYuan+=1;
this.notifyAll();//唤醒所有等待线程
} else if (money == 10) {
System.out.println("杨先生您好!您给的是十元整,找零(五元整)您买的票请收好。");
this.tenYuan +=1;
this.notifyAll();//唤醒所有等待线程
} else if (money == 20) {
while (fiveYuan < 3) {
try {//抛异常
this.wait(); //如果找不开则执行线程等待让排在后面有零钱的人先买。
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.twentyYuan += 1;
this.fiveYuan -= 3;
System.out.println("王先生您好!您给的是二十元整,找零(十五元整),久等了,您买的票请收好。");
}
}
}
//开启线程测试类(可理解为 买票类对象)
class threadOpening implements Runnable{
/* private sellTicket SellTicket = null;
public void threadOpening(sellTicket SellTicket){
this.SellTicket=SellTicket;
}
*/
static Thread MrLi,MrYang,MrWng;
static sellTicket missSellTicket;
@Override
public void run() {
if(Thread.currentThread()==MrLi){
missSellTicket.Sell(5);
}else if(Thread.currentThread()==MrYang){
missSellTicket.Sell(10);
}else if(Thread.currentThread()==MrWng){
missSellTicket.Sell(20);
}
}
public static void main(String[] args){
threadOpening TO = new threadOpening();
MrLi = new Thread(TO);
MrYang = new Thread(TO);
MrWng = new Thread(TO);
missSellTicket = new sellTicket();
MrWng.start();
MrLi.start();
MrYang.start();
}
}
/*---------------------
作者:东方神祇
本文链接:https://my.oschina.net/yangmufa/blog/3084464
版权声明:
本文为博主原创文章,转载请附上源文链接!
如果觉得我的论文对你有用,你的请评论点赞与
合理优质的转发也将是鼓励支持我继续创作的动力!
---------------------*/