我正在尝试在 Java 中解决以下问题:
有一个酒吧,吸烟和不吸烟的顾客都可以去。酒吧为顾客提供的座位数量有限。吸烟和不吸烟的顾客不能同时出现在酒吧里。每个顾客都会花一些时间去酒吧,然后进入,在酒吧里呆一段时间,最后离开,腾出座位让其他等待进入的顾客。吸烟的顾客离开酒吧后,需要更新里面的空气这样不吸烟的顾客就可以来了。
使用 Java 中的线程同步方法创建此问题的简单模拟,并确保不会发生死锁。
我能想出的是以下代码。我有一个问题 -如何实现需要在刷新空气所需的时间内锁定酒吧的条件?
这是代码:
class Bar {
int maxP;
int curP;
String state;
public Bar(int maxP) {
this.maxP = maxP;
curP = 0;
state = "none";
}
public synchronized void enterBar(Customer customer) {
if(state == "none") {
state = customer.smokingStatus;
}
while((curP == maxP) || state != customer.smokingStatus) {
System.out.println(customer.name+" " + customer.smokingStatus + " is waiting to enter the bar. ");
try {
wait();
if(curP == 0 && state == "none") {
state = customer.smokingStatus;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
curP++;
System.out.println(customer.name +" "+ customer.smokingStatus + " enters the bar and relaxes. ");
}
public synchronized void leaveBar(Customer customer) {
curP--;
if(curP == 0) {
state = "none";
}
System.out.println(customer.name +" " + customer.smokingStatus + " stops relaxing and leaves the bar.");
notifyAll();
}
}
然后类客户:
class Customer extends Thread {
String name;
String smokingStatus;
Bar bar;
public Customer(String name, String smoker, Bar bar) {
this.name = name;
this.smokingStatus = smoker;
this.bar = bar;
}
public void run() {
System.out.println(this.name + " is traveling to the bar.");
try {
sleep((int)(Math.random()*1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
bar.enterBar(this);
try {
sleep((int)(Math.random()*5000));
} catch (InterruptedException e) {
e.printStackTrace();
}
if (this.smokingStatus.equals("smoker")){
System.out.println("After I've been here the bar's air needs some refreshing.");
try {
sleep((int)(Math.random()*2000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
bar.leaveBar(this);
}
}
最后是 main() 方法:
class MainApp {
public static void main(String args[]) {
Bar s = new Bar(5);
for(int i = 0; i < 10; i++) {
String smokingStatus;
smokingStatus = Math.random() > 0.5 ? "smoker" : "nonsmoker";
(new Customer("Customer " + i, smokingStatus, s)).start();
}
}
}
如何锁定酒吧以清新空气?