The wait/notify () keyword applies to a thread that notifies another thread that the required condition state is ready, most commonly used when a thread sleeps in a loop until the scene gets a specific condition. For example, a thread waits until one component in the queue is able to handle it, and another thread wakes up the waiting thread when the component is added to the queue.
The following code demonstrates collaboration between threads:
Package Thread_waitnotify;public class Productfactory {class Worker implements Runnable {private final OBJ ECT LockObject=NewObject (); Private volatile BooleanHaswork =false; PrivatevoidWaittaketask () { synchronized (lockobject) { while(!haswork) { Try{System.out.println ("Waiting in ..."); LockObject. wait (); } Catch(interruptedexception e) {e.printstacktrace (); }} taketask (); }} PrivatevoidTaketask () {BooleanTmphaswork =false; synchronized (LockObject) { if(haswork) tmphaswork=true; } if(tmphaswork) {System.out.println ("Start doing the task ..."); Try{Thread.Sleep (3000); Synchronized (lockobject) {haswork=false; } } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Task completed, rest after 3s exit ..."); Try{Thread.Sleep (3000); } Catch(interruptedexception e) {e.printstacktrace (); } //System.out.println ("task complete, continue looking for the next task ..."); //Taketask ();}Else{System.out.println ("Temporarily no task, enter the waiting state ..."); Waittaketask (); }} PublicvoidNotifychange () {synchronized (lockobject) {haswork=true; System.out.println ("Get up and start ..."); LockObject. Notifyall ();//Wake up all threads waiting to get lockobject lock}} @Override publicvoidrun () {taketask (); }} public staticvoidMain (string[] args) throws Interruptedexception {worker worker=NewProductfactory ().NewWorker (); Thread Thread=NewThread (worker); Thread.Start (); Thread.Sleep (3000);//Wake Child thread after main thread sleeps 3sWorker.notifychange ();//The main thread sets the semaphore in the child thread and wakes up the blocked threadthread. Join ();//The main thread blocks, waiting for the child thread to finish executing the main threadSystem.out.println ("Sub-thread execution completes, the main thread exits.") "); System.exit (0); }}
The execution results are as follows:
Talk about the relationship between synchronized and wait (), notify ():
1. There is not necessarily a wait,notify in a synchronized place.
2. There must be synchronized where there is wait,notify. This is because wait and notify are not thread classes, but are methods that each object has, and both methods are related to object locks, and there must be synchronized in place of locks.
Usage of keyword synchronized,wait,notify for inter-threading collaboration in Java