嗨,我正在研究理发师 sleep 的问题。此外,当他们到达时,他们会排在队伍的前面,并且是下一个理发的人。
我正在使用链接列表
,如果我看到优先客户,我会将他放在列表的开头,如果客户不是优先客户,他会转到列表的末尾。然后我调用 WantHaircut 方法来获取列表的第一个元素。
我的问题是,客户按照到达的顺序进行处理,而优先客户必须等待。这是发生这一切的代码。有什么想法我做错了吗?谢谢
public void arrivedBarbershop(Customer c){
if(waiting < numChairs && c.isPriority()){
System.out.println("Customer " + c.getID() + ": is a priority customer - SITTING -");
mutex.up();
customer_list.addFirst(c);
}
else if(waiting >= numChairs && c.isPriority()){
System.out.println("Customer " + c.getID() + ": is a priority customer - STANDING -");
mutex.up();
customer_list.addFirst(c);
}
else if(waiting < numChairs && !c.isPriority()){
waiting++;
System.out.println("Customer " + c.getID() + ": arrived, sitting in the waiting room");
customer_list.addLast(c);
customers.up(); // increment waiting customers
}
else if(waiting >= numChairs && !c.isPriority()) {
System.out.println("Customer " + c.getID() + ": went to another barber because waiting room was full - " + waiting + " waiting");
mutex.up();
}
if(!customer_list.isEmpty()){
this.wantHairCut(customer_list.removeFirst());
}
}
public void wantHairCut(Customer c) {
mutex.up();
barber.down(); // waits for being allowed in barber chair
System.out.println("Customer " + c.getID() + ": getting haircut");
try {
/** haircut takes between 1 and 2 seconds **/
Thread.sleep(Barbershop.randomInt(1, 2) * 1000);
} catch (InterruptedException e) { }
System.out.println("Barber: finished cutting customer " + c.getID() + "'s hair");
c.gotHaircut = true;
cutting.up(); // signals cutting has finished
/** customer must pay now **/
this.wantToCashout(c);
}
最佳答案
您必须使用同步集合:
Collections.synchronizedList(List<Object> list)
该方法根据参数列表返回同步的List实例
关于Java 线程无法与链表正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2574834/