嗨我正在研究睡覺的理髮師問題。隨着優先顧客的到來,他們會在行的前面,他們是下一個理髮。Java線程無法與鏈接表正常工作
我使用的是linkedlist
,如果我看到一個優先客戶,我把他放在列表的開頭,如果客戶不是優先級,他會到列表的末尾。然後我調用獲取列表的第一個元素的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);
}
什麼是「numChairs」? – Roman 2010-04-04 15:12:37
這就是等候室裏椅子的數量。如果他們都把客戶留下,除非他是優先客戶,那麼他可以等待。 – user69514 2010-04-04 16:03:32
因爲向量是線程安全的,所以我使用了一個向量而不是鏈表,但是我仍然有同樣的問題。我不知道我做錯了什麼。 – user69514 2010-04-04 16:04:09