看操作系统的IPC问题发现有个理发师睡觉问题觉得挺有意思,然后想着用java模拟一下,因为平时也比较垃圾,作为初级猿没怎么用过多线程,刚好练着玩玩,然后中间遇到点问题就想着直接找百度看看标答,结果发现没怎么有相关的帖子,最后写出了个简陋版,分享一下,仅作参考,我这估计大佬们看着会看出写问题来,有问题提,但我不一定及时看到。
题目:理发店里有一位理发师、一把理发椅和n把供等候理发的顾客坐的椅子。如果没有顾客,则理发师便在理发椅上睡觉,如图2-20所示。当一个顾客到来时,他必须先叫醒理发师,如果理发师正在理发时又有顾客来到,则如果有空椅子可坐,他们就坐下来等。如果没有空椅子,他就离开。
图片是《操作系统的设计与实现》中的插图,我这里实现是把椅子数设为6,然后设置只有一个理发师,所以我直接用的一个布尔标识的理发师是否睡觉。
public class HaircutIPC {
// 等候理发的顾客(不包括正在理发的顾客)
public static volatile int customers;
// 理发师是否睡眠
public static volatile boolean isSleep;
// 椅子数
public static final int chair = 6;
public static void main(String[] args) {
// 理发师线程,如果等待理发的顾客数为零就睡眠,不为零就起来理发
Thread haircutT = new Thread(()->{
while (true){
// 控制循环速度
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (HaircutIPC.isSleep) {
System.out.println("理发师在睡觉!");
continue;
}
if (HaircutIPC.customers > 0){
//剪头
try {
System.out.println("开始剪头------------------->顾客数" + customers);
Thread.sleep(HaircutIPC.getRandomLong());
HaircutIPC.customers--;
System.out.println("结束剪头------------------->顾客数" + customers);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
// 睡觉
HaircutIPC.isSleep = true;
System.out.println("理发师睡觉了");
}
}
});
// 顾客线程,看看等待理发的顾客数量是否小于椅子数,小于就进来等,不然就不进来,要是理发师睡了还得喊一下理发师
Thread customerT = new Thread(()->{
while (true){
// 控制随机间隔1-10秒
try {
Thread.sleep(HaircutIPC.getRandomLong());
} catch (InterruptedException e) {
e.printStackTrace();
}
if (HaircutIPC.chair > HaircutIPC.customers){
HaircutIPC.customers ++;
// 在睡觉就喊起来
if (HaircutIPC.isSleep){
System.out.println("理发师起来干活了快");
HaircutIPC.isSleep = false;
}
System.out.println(Thread.currentThread().getName() + "--->进入顾客一个,顾客数" + customers);
}
}
});
customerT.setName("customerT");
haircutT.setName("haircutT");
haircutT.start();
customerT.start();
}
public static long getRandomLong(){
return new Double(Math.random()*10000).longValue();
}
}
运行结果如下:



