使用多线程模拟电影院买票。

tech2024-12-01  6

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

package com.softeem.homework3; public class Test7 { public static void main(String[] args) { BuyTicket2 bt = new BuyTicket2(); new Thread(bt,"唐僧").start(); new Thread(bt,"孙悟空").start(); new Thread(bt,"猪八戒").start(); new Thread(bt,"沙僧").start(); } } class BuyTicket2 implements Runnable{ private int tenCount = 1; //10元的张数 private int twentyCount = 0; //20元的张数 public void run() { String name = Thread.currentThread().getName(); //判断过来买票的是谁 if(name.equals("唐僧")){ buy(50); }else if(name.equals("沙僧")){ buy(10); }else{ buy(20); } } //买票的方法 public synchronized void buy(int money){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if(money == 10){ //拿10元来买票,直接买票 tenCount += 1; System.out.println(Thread.currentThread().getName()+"花"+money+"元买了一张票"); notifyAll(); }else if(money == 20){ //拿20元来买票,判断是否有钱找零 while(tenCount < 1){ System.out.println(Thread.currentThread().getName()+"拿20元来买票,找不开,到旁边等着"); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } tenCount -= 1; twentyCount += 1; System.out.println(Thread.currentThread().getName()+"花"+money+"元买了一张票,找了"+(money-10)+"元"); notifyAll(); }else{ //拿50元来买票,判断是否有钱找零 while(((tenCount < 2 && twentyCount < 1) || (twentyCount < 2))){ System.out.println(Thread.currentThread().getName()+"拿50元来买票,找不开,到旁边等着"); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //判断售票员手上所持有的哥哥面值钱币的张数给出相应找钱方法 if(twentyCount < 2){ tenCount -= 2; twentyCount -= 1; }else{ twentyCount -= 2; } System.out.println(Thread.currentThread().getName()+"花"+money+"元买了一张票,找了"+(money-10)+"元"); notifyAll(); } } }
最新回复(0)