ฉันยังใหม่กับ Java multithreading และเขียนโปรแกรมขนาดเล็กเพื่อทดสอบว่า wait() และ notifyAll() วิธีการโต้ตอบกันอย่างไร แต่ทำไมโปรแกรมนี้ถึงใช้ไม่ได้
package sample;
public class Main {
public static void main(String[] args) {
new Thread(new MyWriter()).start();
new Thread(new MyReader()).start();
}
}
class MyReader implements Runnable {
@Override
public synchronized void run() {
while(true) {
notifyAll();
}
}
}
class MyWriter implements Runnable {
@Override
public synchronized void run() {
while(true) {
try {
System.out.println("Waiting...");
wait();
System.out.println("Wait Terminated");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
เมื่อวิ่งฉันคาดว่าผลลัพธ์จะเป็น
Waiting...
Wait Terminated
แต่มันออก
Waiting...
และรอตลอดไปจนกว่าฉันจะยุติมันด้วยตนเอง