Java provides 3 very important ways to skillfully solve communication problems between threads. These 3 methods are: Wait (), notify (), and Notifyall (). They are all the final methods of the object class, so each class has them by default.
Although all classes have these 3 methods by default, they are only meaningful if the Synchronized keyword is scoped to the same synchronization problem and is used in conjunction with the 3 methods.
-
If the object calls the wait method, it causes the thread holding the object to hand over the object's control and then waits.
-
If an object calls the Notify method, it notifies a thread that is waiting for control of the object to continue running.
-
If the object calls the Notifyall method, all threads waiting for control of the object will be notified to continue running.
This is illustrated by an example of 2 threads, which alternately print a, B
package com.smart.concurrency.chapter2;/** * @Description * @author Gaowenming */public class waitandnotifytest { public static final object obj = new object (); public static void main (String[] args) throws Exception { thread t0 = new thread (New thread0 ()); thread t1 = new thread (New thread1 ()); t0.start (); t1.start (); }}class Thread0 implements Runnable { @Override public void run () { while (True)  {    &Nbsp; synchronized (waitandnotifytest.obj) { try { Thread.Sleep (; ) system.out.println ("A"); waitandnotifytest.obj.notify (); WaitAndNotifyTest.obj.wait (); } catch (exception e) { &Nbsp; e.printstacktrace (); } } } }}class thread1 implements Runnable { @Override public void run () { while (true) { synchronized (waitandnotifytest.obj) { try { thread.sleep (; ) &nbsP; system.out.println ("B"); waitandnotifytest.obj.notify (); waitandnotifytest.obj.wait (); } catch (exception e) { e.printstacktrace (); } } } }}
Code, you can see that 2 threads are monitoring the same object waitandnotifytest.obj to ensure that the synchronization operation is valid
Abababababab
Implementation of inter-thread communication wait () and notify () methods