เมื่อ wait() ถูกเรียกบนออบเจ็กต์ จะทำให้ current thread รอจนกว่า thread อื่นจะ.invoke notify() หรือ notifyAll() สำหรับออบเจ็กต์นี้ ในขณะที่ wait(long timeout) ทำให้ current thread รอจนกว่าจะมี thread อื่น invoke notify() หรือ notifyAll() สำหรับออบเจ็กต์นี้ หรือ timeout ที่ระบุหมดเวลาแล้ว
wait()
ในโปรแกรมด้านล่าง เมื่อ wait() ถูกเรียกบนออบเจ็กต์ thread จะเปลี่ยนสถานะจาก running เป็น waiting state รอ thread อื่นเรียก notify() หรือ notifyAll() เพื่อเข้าสู่ runnable state จะเกิด deadlock หากไม่มี thread อื่นเรียก notify
ตัวอย่าง
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();
}
}
Output
In run() method
wait(long)
ในโปรแกรมด้านล่าง เมื่อ wait(1000) ถูกเรียกบนออบเจ็กต์ thread เข้าสู่ waiting state แม้ notify() หรือ notifyAll() จะไม่ถูกเรียก หลังจาก timeout หมดเวลา thread จะกลับสู่ runnable state
ตัวอย่าง
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();
}
}
Output
In run() method Thread in waiting state, waiting for some other threads on same object to call notify() or notifyAll()