যখন কোনো অবজেক্টের ওপর 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()