好吧,我是第二学期的学生,现在我们要通过线程。我大部分时间都得到了它,但关于我的一个练习并没有结果,我无法理解它。
“在一家面包店,你经常需要在到达商店时拿一个号码,然后等到它是你的 转(用正确的号码)。“ 我打算在显示器中复制粘贴方法,我认为这可能是问题所在。
private NumberDispenser(){
nextNoToTake=1;
nextNoToServe=0;
}
public static NumberDispenser accessDispenser(){
if(theOne == null){
theOne = new NumberDispenser();
}
return theOne;
}
@Override
public synchronized void takeNextNumber() {
int currNo = nextNoToTake;
nextNoToTake++;
notifyAll();
System.out.println("No:"+currNo+" has been taken|nextNoToServe:"+nextNoToServe);
while(currNo != nextNoToServe)
{try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("No:"+currNo+" has been served");
notify();
}
@Override
public synchronized int nextCustomer() {//Serves the current customer and goes to the next one
System.out.println("Clerk is ready to deal with a new customer");
while((nextNoToServe)>=nextNoToTake-1)
try {
wait();
} catch (InterruptedException e) {}
nextNoToServe++;
notifyAll();
System.out.println("Now serving No:"+(nextNoToServe));
return nextNoToServe;
}
这是监控类。对于客户和秘书,还有两个用于测试。客户类有Thread.sleep来模拟浏览时间然后进入dispenser.takeNextNumber();之后它应该完成并且负责它的线程应该自己死(在主类中).Clerk循环dispenser.nextCustomer(无休止地延迟。主要方法在单独的for循环中创建了许多客户及其线程,以及一些职员及其线程。
/////这是从要求中粘贴的副本。 客户到达和职员服务由线程模拟。
实现一个实现接口TakeANumber的NumberDispencer类作为监视器。 提示:您可以定义两个实例变量 private int nextNumberToTake = 1; private int nextNumberToServe = 1;
实现两个线程类: 一个线程类,它模拟客户获取数字并获得服务 模拟职员服务的线程类,即获取下一个客户编号然后进行编制 服务。
使用main方法实现一个类来模拟面包店,例如两名服务员和十名 顾客。 /////
我几乎修复了代码。问题出在while循环的情况下。现在它几乎按预期工作,但它跳过了第一个客户。只有第一个客户被跳过,然后一切都按照应有的方式进行。
答案 0 :(得分:0)
我可以看到一个被打破的地方。
提示:假设有一个服务器和一个客户,服务器在客户到达之前调用nextCustomer()
。当客户到达时会唤醒什么?
此外,这句话是一个黑客。
if (nextNoToServe == 0)
nextNoToServe = 1;
应该通过将实例变量初始化为适当的值来处理;例如在构造函数中。