java 买票 多线程_Java 多线程同步机制-车站购票系统问题简单模拟处理(BuyticketMultithreadingDemo)...

//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();

}

}

/*-------------------反爬声明o(*▽*)咻咻咻--------------------

作者:版权声明:本文为博主倾情原创文章,整篇转载请附上源文链接!

如果觉得本文对你有所收获,你的请评论点赞 与

合理优质的转发也将是鼓励支持我继续创作的动力,

更多精彩可百度搜索 杨木发 或:

坚持创作 善于总结 开源共享 高质进步。

-------------------反爬声明o(*▽*)咻咻咻--------------------*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值