Wait and notify are synchronous and mutually exclusive by locking objects.
The wait and notify functions need to be in a section of the synchronization code, that is, in the synchronized code snippet.
A simple example code.
Static class Testthread {public Boolean locked = false;public void Run () {long last = System.currenttimemillis (); Synchroni Zed (Locked) {while (locked) {//release this lock? try {System.out.println (Thread.CurrentThread (). toString () + "Now is Waiting");//The result of the final test is that if the wait is not written at a specific time, The other notify won't wake the lock. Locked.wait (1000); System.out.println (Thread.CurrentThread (). toString () + "Waiting is End"); catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} System.out.println (Thread.CurrentThread (). toString ()//+ "lock locked"); locked = true;//work. System.out.println (Thread.CurrentThread (). toString ()//+ "work start");//System.out.println ( Thread.CurrentThread (). toString ()//+ "work start locked" + locked), Long now = System.currenttimemillis (), while (Now-la St < +) {locked = True;now = System.currenttimemillis ();} Locked = false;//System.out.println (Thread.CurrentThread (). toString ()//+ "work end notify"); synchronized (locked) {lo Cked.notifyall (); SystEm.out.println (Thread.CurrentThread (). toString () + "work end Notify");} System.out.println (Thread.CurrentThread (). toString ()//+ "work finished");}} /** * @param args */public static void main (string[] args) {final Testthread tt = new Testthread (); for (int i = 0; i < 5; i++) {New Thread (new Runnable () {public void run () {Tt.run ()}}). Start ();}
The output is:
Thread[thread-2,5,main] is waiting
Thread[thread-3,5,main] is waiting
Thread[thread-4,5,main] is waiting
Thread[thread-1,5,main] Work End Notify
Thread[thread-0,5,main] Work End Notify
Thread[thread-2,5,main] Waiting is end
Thread[thread-2,5,main] Work End Notify
Thread[thread-3,5,main] Waiting is end
Thread[thread-3,5,main] Work End Notify
Thread[thread-4,5,main] Waiting is end
Thread[thread-4,5,main] Work End Notify
Here I lock the Boolean object locked in Testthread. The locked object is locked by synchronized (locked), but locked.wait (1000) Also releases the locked object lock, causing other threads to access the locked object. Then the freed object is used by other threads after the end, using Locked.notifyall (); Notifies other threads waiting on the object that the current object can be used. The thing to note here is that the wait () thread will be alerted and get the object lock to continue running, but in fact I test the result is not like this, if I do not set the time here 1000ms, when using notify or Notifyall, is unable to restart the thread, it should be set for a certain amount of time for the thread to detect itself.
Wait and notify in Java Multi-threading