我不知道該怎麼做!我是初學者, 工作正常,但裏面的方法notifyAll()
將不會通知wait()
。爲什麼wait()在notifyAll()被調用後無法工作
public class Doctor extends Thread {
public static void main(String[] args) {
Doctor doctor = new Doctor();
Patient patient1 = new Patient(doctor);
Patient patient2 = new Patient(doctor);
patient1.setName("Patient One");
patient2.setName("Patient Two");
patient1.start();
patient2.start();
}
}
//這是Patient類
class Patient extends Thread {
Doctor d;
static boolean isAlready = false;
public Patient(Doctor d) {
this.d = d;
}
public void run() {
synchronized(this) {
if (isAlready == false) {
isAlready = true;
try {
System.out.println(Thread.currentThread().getName() + " Wait to see Doctor\n");
wait();
checkup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
checkup();
}
}
public void checkup() {
synchronized(this) {
try {
System.out.println(Thread.currentThread().getName() + " Enter Doctor's Room!\n");
System.out.println("After Consulting Doctor! '" + Thread.currentThread().getName() + "' Paid fees to Doctor\n");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " Notify to next Patient to enter Doctor's Room!\n");
notifyAll();
System.out.println(Thread.currentThread().getName() + " Leaves Hospital\n");
} catch (Exception e) {
}
isAlready = false;
}
}
}
您好,歡迎您提供儘可能多的信息 – epoch
什麼時候調用checkup方法(run方法除外)? – ortis
所有的病人都會等到另一個病人打電話給'notifyAll'... 所以沒有病人打電話給notifyAll,從不(因爲所有的病人都在等待)...... XD – inigoD