เมื่อใดก็ตามที่ รอ() เมธอดถูกเรียกบนอ็อบเจ็กต์ ทำให้เธรดปัจจุบันรอจนกว่าเธรดอื่นจะเรียกใช้ notify() หรือ notifyAll() วิธีการสำหรับวัตถุนี้ในขณะที่ รอ (หมดเวลานาน) ทำให้เธรดปัจจุบันรอจนกว่าเธรดอื่นจะเรียกใช้ notify() หรือ notifyAll() เมธอดสำหรับอ็อบเจ็กต์นี้ หรือหมดเวลาที่กำหนดแล้ว
รอ()
ในโปรแกรมด้านล่าง เมื่อ รอ() ถูกเรียกบนวัตถุ เธรดเข้าสู่จาก วิ่งไปยังสถานะรอ . มันรอให้เธรดอื่นเรียก notify() หรือ notifyAll() เพื่อให้สามารถเข้าสู่สถานะที่รันได้ การหยุดชะงัก จะก่อตัวขึ้น
ตัวอย่าง
class MyRunnable implements Runnable {
public void run() {
synchronized(this) {
System.out.println("In run() method");
try {
this.wait();
System.out.println("Thread in waiting state, waiting for some other threads on same object to call notify() or notifyAll()");
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}
public class WaitMethodWithoutParameterTest {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable, "Thread-1");
thread.start();
}
} ผลลัพธ์
In run() method
รอ(นาน)
ในโปรแกรมด้านล่าง When wait(1000) ถูกเรียกบนวัตถุ เธรดเข้าสู่จากวิ่งไปยังสถานะรอ แม้ว่าแจ้ง() หรือ notifyAll() ไม่ถูกเรียกหลังจากหมดเวลาหมดเวลา เธรดจะเปลี่ยนจาก สถานะรอเป็นสถานะรันได้
ตัวอย่าง
class MyRunnable implements Runnable {
public void run() {
synchronized(this) {
System.out.println("In run() method");
try {
this.wait(1000);
System.out.println("Thread in waiting state, waiting for some other threads on same object to call notify() or notifyAll()");
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}
public class WaitMethodWithParameterTest {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable, "Thread-1");
thread.start();
}
} ผลลัพธ์
In run() method Thread in waiting state, waiting for some other threads on same object to call notify() or notifyAll()