我正在使用线程编写一个理发店程序。目前我有一个理发师和多个客户同时进来。然而,在第一次运行程序之后,其余的客户都搞砸了。他们都同时坐下。有什么我错过的吗?我的代码是:
public synchronized void enter(Customer cust) {
custList.add(cust);
getCut(cust);
}
public synchronized void getCut(Customer cust) {
try {
notify();
wait();
System.out.println("sit down");
notify();
if (cashier==0) {
cashier++;
wait();
System.out.println("waiting to pay");
notify();
wait();
System.out.println("left the room");
chairs++;
cust.terminate();
}
} catch (InterruptedException ie) {}
}
这是我的理发师部分:
public synchronized void cut(Barber barb) {
cashier=0;
try {
if(temp){
System.out.println(temp);
temp = false;
notify();
wait(); //wait for the customer to be settled in
System.out.println("go to cus");
notify();
wait();
System.out.println("cut cus hair");
notify();
wait();
if (cashier==1) {
System.out.println("got money");
notify();
cashier--;
barbers++;
}
}
} catch (InterruptedException ie) {}
}
}
public synchronized void goCut(Barber barb) {
cashier=0;
try {
if(temp){
System.out.println(temp);
temp = false;
notify();
wait();
System.out.println("walks to cus");
notify();
wait();
System.out.println("cut hair");
notify()
wait();
if (cashier==1) {
System.out.println("got the money");
notify();
cashier--;
barbers++;
}
}