操作系统-理发师问题的java模拟

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

理发师问题的java语言模拟对于操作系统经典的理发师问题,给出一种基于java代码的解决方案。一、问题分析:我们首先需要考虑以下的情况:1.没有顾客时:理发师休息2.顾客到来但理发师在睡觉时:唤醒理发师3.顾客到来理发师在理发:有空椅子,坐上去等待;没有空椅子,离开,过一会儿再回来二、代码情况说明:设计类Cust实现接口Runnable,用来表示编号为index的顾客的执行情况。类Barbershop中包含主函数,使用方法isEmpty();isBusy();isFull();分别用来检验是否有顾客,理发师的状态,是否有空椅子;使用全局变量sleep来表示理发师是否在睡觉。主函数中使用for循环newThread(newCust(b,i)).start();开始一个进程的执行申请,在haircut()方法之中进行以上三种情况的判断与处理。测试时只需运行BarberShop根据提示输入对应的顾客和椅子数量即可三、具体代码:importjava.util.Scanner;importjava.util.concurrent.Semaphore;publicclassBarbershop{intcustomer=0;//顾客的数量staticintchair=2;//椅子的数量intbusy=0;//理发师是否繁忙booleansleep=true;Semaphoremutex=newSemaphore(1);//信号量的初始值为1publicstaticvoidmain(String[]args)throwsInterruptedException{Barbershopb=newBarbershop();System.out.println(睡觉的理发师问题:\r\n一个理发店包含了一个有n把椅子的等待室,店里有一把椅子供顾客理发。\r\n没有顾客的时候理发师就会睡觉。\r\n如果顾客到来时发现椅子+满了,就会离开。\r\n如果理发师正在忙但是还有空椅子,顾客就会坐在椅子上等候。\r\n如果顾客到来时理发师正在睡觉,那么顾客就会唤醒理发师。);System.out.println(让我们来模拟一下:\r\n会有多少个顾客到来呢?);intcust=Integer.valueOf((newScanner(System.in)).nextLine());System.out.println(理发店里一共有多少把椅子呢?(包括正在理发的那个顾客的椅子));chair=Integer.valueOf((newScanner(System.in)).nextLine());System.out.println(好的,+cust+名顾客和+chair+把椅子。现在,我们开始吧。\r\n--------------------------------------------------------------------------);for(inti=1;icust+1;i++){newThread(newCust(b,i)).start();Thread.sleep((int)(400-Math.random()*300));//使得当前线程休眠随机0-0.1s}}publicsynchronizedbooleanisFull(){//检验有没有空椅子if(customer=chair){returntrue;}returnfalse;}publicsynchronizedbooleanisEmpty(){//检验是否有顾客if(customer=0){returntrue;}returnfalse;}publicsynchronizedbooleanisBusy(){//检验理发师的状态if(busy=1){returntrue;}returnfalse;}publicvoidhaircut(intindex)throwsInterruptedException{booleanhaveHaircut=false;while(!haveHaircut){System.out.println(顾客+index+:我来理发啦~);customer++;//判断是否满if(isFull()){System.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(sleep){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)){sleep=true;System.out.println(理发师:诶呀现在没有人来理发,可把我给累坏了,让我打个盹儿~);}}}}packageoperationSystem;publicclassCustimplementsRunnable{Barbershopdohair;intindex;publicCust(Barbershopdohair,intindex){this.dohair=dohair;this.index=index;}publicvoidrun(){try{dohair.haircut(index);}catch(InterruptedExceptione){e.printStackTrace();}}}

1 / 4
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功