1、理发师问题的java语言模拟对于操作系统经典的理发师问题,给出一种基于java代码的解决方案。一、问题分析:我们首先需要考虑以下的情况:1.没有顾客时:理发师休息2.顾客到来但理发师在睡觉时:唤醒理发师3.顾客到来理发师在理发:有空椅子,坐上去等待;没有空椅子,离开,过一会儿再回来二、代码情况说明:设计类 Cust 实现接口Runnable,用来表示编号为index的顾客的执行情况。类Barbershop中包含主函数,使用方法isEmpty();isBusy();isFull();分别用来检验是否有顾客,理发师的状态,是否有空椅子;使用全局变量sleep来表示理发师是否在睡觉。主函数中使用fo。
2、r循环new Thread(new Cust(b, i).start();开始一个进程的执行申请,在haircut()方法之中进行以上三种情况的判断与处理。测试时只需运行BarberShop根据提示输入对应的顾客和椅子数量即可三、具体代码:import java.util.Scanner;import java.util.concurrent.Semaphore;public class Barbershop int customer = 0; /顾客的数量static int chair = 2; /椅子的数量int busy = 0; /理发师是否繁忙boolean sleep = tru。
3、e;Semaphore mutex = new Semaphore(1); /信号量的初始值为1public static void main (String args) throws InterruptedException Barbershop b =new Barbershop();System.out.println(睡觉的理发师问题:rn一个理发店包含了一个有n把椅子的等待室,店里有一把椅子供顾客理发。rn没有顾客的时候理发师就会睡觉。rn如果顾客到来时发现椅子+ 满了,就会离开。rn如果理发师正在忙但是还有空椅子,顾客就会坐在椅子上等候。rn如果顾客到来时理发师正在睡觉,那么顾客就。
4、会唤醒理发师。);System.out.println(让我们来模拟一下:rn会有多少个顾客到来呢?);int cust = Integer.valueOf(new Scanner(System.in).nextLine();System.out.println(理发店里一共有多少把椅子呢?(包括正在理发的那个顾客的椅子);chair = Integer.valueOf(new Scanner(System.in).nextLine();System.out.println(好的,+cust+名顾客和+chair+把椅子。现在,我们开始吧。rn-);for (int i = 1; i =cha。
5、ir) return true;return false;public synchronized boolean isEmpty() /检验是否有顾客if (customer= 1) return true;return false;public void haircut(int index) throws InterruptedException boolean haveHaircut = false;while(!haveHaircut) System.out.println(顾客 + index + :我来理发啦);customer+;/ 判断是否满if (isFull() System。
6、.out.println(顾客 + index + :嘤嘤嘤,没有椅子了,我一会儿再过来看看吧);customer-;Thread.sleep(int) (6000 - Math.random() *3000); /顾客在一定的时间之后会回来 else if (busy = 1) System.out.println(顾客 + index + :有空椅子!我先坐上去!);System.out.println(顾客 + index + :等啊等,怎么还不到我呀?);mutex.acquire();synchronized (this) while (busy = 1) wait();if(sle。
7、ep) System.out.println(顾客 + index + :理发师,醒来啦 );sleep = false;System.out.println(顾客 + index + :好开心,开始理发了!);busy = 1;Thread.sleep(1000); /理发需要一定的时间System.out.println(顾客 + index + :我的新发型好漂亮!我走啦!);haveHaircut = true;customer-;mutex.release();synchronized (this) busy = 0;notify();if (customer = 0&(!sleep。
8、) sleep = true;System.out.println(理发师:诶呀现在没有人来理发,可把我给累坏了,让我打个盹儿);package operationSystem;public class Cust implements Runnable Barbershop dohair;int index;public Cust(Barbershop dohair, int index) this.dohair = dohair;this.index = index;public void run() try dohair.haircut(index); catch (InterruptedException e) e.printStackTrace(。