Home >Java >javaTutorial >In Java, when can we call Thread's wait() and wait(long) methods?
Whenever the wait() method is called on an object, it causes the current thread to wait until another thread calls notify() or notifyAll( ) method of this object, while wait(long timeout) causes the current thread to wait until another thread calls notify() or notifyAll( ) Method of this object, or the specified timeout period has passed.
In the following program, when wait() is called on an object, the thread enters the waiting state from the running state. It waits for other threads to call notify() or notifyAll() before it can enter the runnable state, which will form a deadlock.
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)
In the following program, Whenwait(1000) is called on an object, the thread enters the waiting state from the running state, even if notify() or is not called after the timeout period. notifyAll()The thread will also enter the runnable state from the waiting state.
Exampleclass MyRunnable implements Runnable { public void run() { synchronized(this) { System.out.println("In run() method"); try { <strong> this.wait(1000); </strong> 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()
The above is the detailed content of In Java, when can we call Thread's wait() and wait(long) methods?. For more information, please follow other related articles on the PHP Chinese website!