Java线程模仿电影院买票

模拟唐僧师徒4人买电影票。电影票10元一张,唐僧拿着一张50元的、孙悟空那和 猪八戒都拿着一张20的、 沙僧拿着一张10元的。此时售票员手中只有一个10元的。 模拟他们4个人买票。


package com.wxh.day1015;

//唐僧 50 孙悟空 20 八戒 20 沙僧10
//售票员 10
//电影票10块一张

public class Demo2 {	
	public static void main(String[] args) {
		SThread st=new SThread();
		new Thread(st,"唐僧").start();
		new Thread(st,"孙悟空").start();
		new Thread(st,"八戒").start();
		new Thread(st,"沙僧").start();
	}

}

class SThread implements Runnable{
	private int tenCount=1;
	private int twentyCount=0;
	
	public void run() {
		if(Thread.currentThread().getName().equals("唐僧")){
			sell(50);			
		}else if(Thread.currentThread().getName().equals("孙悟空")){
			sell(20);
		}else if(Thread.currentThread().getName().equals("八戒")){
			sell(20);
		}else if(Thread.currentThread().getName().equals("沙僧")){
			sell(10);
		}
	}

	private synchronized void sell(int i) {
		if(i==10){
			tenCount++;
			System.out.println(Thread.currentThread().getName()+"拿来了一张10圆的,买了一张电影票");
			notifyAll();
		}else if(i==20){
			while(tenCount<1){
				System.out.println(Thread.currentThread().getName()+"拿来了一张20圆的,售票员找不开,在旁边等着。");
				try {
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}			
			}
			
			tenCount--;
			twentyCount++;
			System.out.println(Thread.currentThread().getName()+"拿来一张20圆的,买了一张电影票,找回10圆");
			notifyAll();
		}else if(i==50){
			while(tenCount*10+twentyCount*20<40){
				System.out.println(Thread.currentThread().getName()+"拿了一张50的,售票员找不开,在旁边等着");
				try {
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			twentyCount-=2;
			System.out.println(Thread.currentThread().getName()+"拿了一张50的,买了一张电影票,找回2张20的");
			notifyAll();
		}
		
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}	
		
	}
	
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值