请根据自己的实际情况选择一种语言的进程/线程同步工具进行学习,并尝试使用该工具实现睡觉的理发师问题的解决方案
Barber类
public class Barber implements Runnable {
Barbershop barbershop;
int index;
@Override
public void run() {
// TODO Auto-generated method stub
try {
barbershop.simulate(index);
}catch(InterruptedException e){
e.printStackTrace();
}
}
public Barber (Barbershop bs,int i) {
this.barbershop=bs;
index=i;
}
}
Barbershop类
import java.util.concurrent.Semaphore;
public class Barbershop {
static int customer=0;//当前顾客数
static int MAX=5;//提供的让顾客等待的椅子数
static int busy=0;//理发师是否忙碌标识
static Semaphore mutex=new Semaphore(1);//信号量,只允许一个顾客占用理发师
public synchronized boolean isFull() {
//判断是否为满
if(customer==MAX) {
return true;
}
return false;
}
public synchronized boolean isEmpty() {
// 判断是否为空
if(customer==0) {
return true;
}
return false;
}
public void simulate(int index) throws InterruptedException {
// 模拟函数
System.out.println("customer "+index+" come");
customer++;
if(isFull()) {
// 如果为满顾客离开
System.out.println("no chair for customer,"+"customer "+index+" left");
customer--;
}
else {
if(busy==1) {
// 如果理发师忙碌,顾客等待
System.out.println("customer "+index+" is waiting for the barber");
}
mutex.acquire();
// 信号量减,防止其他进程再进入
synchronized (this) {
// 同步
while (busy==1) {
wait();
// 有人理发等待
}
}
if(customer==1) {
// 只有一个顾客
System.out.println("there is only customer :customer "+index+" in the barbershop,the barber is working ");
}
busy=1;
System.out.println("custoemr "+index+" is having a haircut");
Thread.sleep(1000);
//理发时间1000毫秒
System.out.println("customer "+index+" left");
customer--;
mutex.release();
// 释放资源
synchronized(this) {
// 同步并唤醒
busy=0;
notify();
}
if(customer==0) {
// 没有顾客,理发师睡觉
System.out.println("the barber start to sleep");
}
}
}
public static void main(String[] args) throws InterruptedException {
Barbershop barbershop= new Barbershop();
for (int i =1;i<=10;i++) {
// 假设一共有10个顾客
new Thread(new Barber(barbershop,i)).start();
Thread.sleep((int)(600-Math.random()*500));
}
}
}
运行结果: