Wait (), notify (), Notifyall () and other methods introduced
In Object.java, interfaces such as Wait (), notify (), and notifyall () are defined. The function of Wait () is to let the current thread into the waiting state, while the () will also let the current thread release the lock it holds. The role of Notify () and Notifyall () is to wake up the waiting thread on the current object, notify () is to wake up a single thread, and Notifyall () is to wake up all the threads.
The API details about wait/wake in the object class are as follows:
Notify ()--wakes up a single thread waiting on this object monitor.
Notifyall ()--wakes up all threads waiting on this object monitor.
Wait ()--leave the current thread in "Waiting (blocking) state" until another thread calls the object's notify () method or Notifyall () method, and the current thread is awakened (into into the ready state).
Wait (long timeout)--keeps the current thread in the "Waiting (blocking) state" until the other thread calls the object's notify () method or Notifyall () method, or exceeds the specified amount of time ", the current thread is awakened (Into the Ready state).
Wait (long timeout, int nanos)--Leave the current thread in "Waiting (blocking) state" until another thread calls the object's notify () method or Notifyall () method, or another thread interrupts the current thread, or has exceeded a certain actual time Quantity, the current thread is awakened (into the ready state).
2. Wait () and notify () examples
The following example shows a scenario where wait () and notify () are used together.
Waittest.java Source class Threada extends thread{public Threada (String name) {super (name); public void Run () {synchronized () {System.out.println () {Thread.CurrentThread (). GetName
() + "Call Notify ()");
Wakes up the current wait thread notify (); }} public class Waittest {public static void main (string[] args) {Threada T1 = new THR
EadA ("T1"); Synchronized (t1) {try {//start thread T1 System.out.println (Thread.CurrentThread ()
. GetName () + "start T1");
T1.start ();
The main thread waits for T1 to be awakened by notify ().
System.out.println (Thread.CurrentThread (). GetName () + "Wait ()");
T1.wait ();
System.out.println (Thread.CurrentThread (). GetName () + "continue");
catch (Interruptedexception e) {e.printstacktrace (); }
}
}
}
Run Result:
Main start T1
Main Wait ()
T1 Call Notify ()
Main continue