Home >Java >javaTutorial >In Java, when can we call Thread's wait() and wait(long) methods?

In Java, when can we call Thread's wait() and wait(long) methods?

WBOY
WBOYforward
2023-09-03 23:41:091020browse

In Java, when can we call Threads 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.

wait()

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.

Example

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)

In the following program, When

wait(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.

Example

class 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();
   }
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete