जब भी किसी ऑब्जेक्ट पर wait() मेथड को कॉल किया जाता है, तो यह करंट थ्रेड को तब तक इंतजार करने का कारण बनता है जब तक कि दूसरा थ्रेड इस ऑब्जेक्ट के लिए notify() या notifyAll() मेथड को इनवोक न करे, जबकि wait(long timeout) करंट थ्रेड को तब तक इंतजार करने का कारण बनता है जब तक कि या तो दूसरा थ्रेड इस ऑब्जेक्ट के लिए notify() या notifyAll() मेथड्स को इनवोक न करे, या एक निर्दिष्ट टाइमआउट समय बीत न जाए।
wait()
नीचे दिए गए प्रोग्राम में, जब किसी ऑब्जेक्ट पर wait() कॉल किया जाता है, तो थ्रेड रनिंग से वेटिंग स्टेट में प्रवेश करता है। यह किसी अन्य थ्रेड के 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
wait(long)
नीचे दिए गए प्रोग्राम में, जब किसी ऑब्जेक्ट पर wait(1000) कॉल किया जाता है, तो थ्रेड रनिंग से वेटिंग स्टेट में प्रवेश करता है, भले ही notify() या 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()