我试图解决在Java中,以下问题与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();
}
}
}
怎么锁定了吧空气清新?
你需要专门的“进修”线程,检查离开的客户是否留下不愉快的气味。进入的非吸烟顾客将检查是否存在异味,并且会阻止直到更新线完成它的工作。 –
为了记录我有点讨厌这个问题,这是多线程的一个荒谬的用法,无论作者希望你想出什么锁定机制,在严肃的代码审查中不会持续10秒。 – djechlin
@djechlin:我个人喜欢它。用*工作线程*和*工具栏*替换*客户*通过*连接池*,你有一个更现实,但更抽象的问题。 –