【发布时间】:2015-04-15 14:06:14
【问题描述】:
我不知道该怎么办!我是初学者,
public void checkUp(){} 工作正常,但内部方法notifyAll() 不会通知wait()。
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();
}
}
//这是患者类
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;
}
}
}
【问题讨论】:
-
您好,欢迎您,您应该尽量提供尽可能多的信息
-
什么时候调用
checkup方法(run方法除外)? -
您的所有患者都等到另一个患者调用“notifyAll”...所以没有患者调用 notifyAll,永远不会(因为所有患者都在等待)...XD
-
如果你想同步很多
Patients,你需要使用共享对象而不是this。现在,notifyAll()仅通知在监视器上等待特定Patient对象的线程,而不是所有线程。
标签: java multithreading tags wait notify