Java线程模仿电影院买票

来源:互联网 发布:云计算行业大事件 编辑:程序博客网 时间:2024/04/30 08:34

模拟唐僧师徒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();}}}


0 0
原创粉丝点击