This three function comes from the object class, which is known to be used for multithreaded synchronization.
However, there is a problem that has not been clear, that is the Notify () function to inform who?
In the thinking in JAVA, when the Notify () function is called because of a particular lock, only the wait
The task of this lock will be awakened.
What do you mean?
Look at the code below, this code execution will be an error, java.lang.IllegalMonitorStateException
Check the Internet, understand.
1> the current thread does not contain the lock resource of the current object, call the Obj.wait () method;
2> the Obj.notify () method is called when the current thread does not contain a lock resource for the current object.
3> the Obj.notifyall () method is called when the current thread does not contain a lock resource for the current object.
Public classAppleImplementsrunnable{ Public StaticObject apple=NewObject (); @Override Public voidrun () {synchronized(apple) {System.out.println ("Apple locked"); Try{wait (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }} System.out.println ("Apple Run End"); }}
Synchronized the above code (apple)
Change to synchronized(this) will not error class
It turns out that the wait function can only be called on a when the front-thread has the lock on object A, and at this point the thread is
Wait on object A.
If other threads call the class A.notify (), then the thread waiting on a will wake up.
Then there is a problem, because the call of the Notify function also needs to obtain the lock of the object, and wait has already obtained this lock, then it is not contradictory?
It turns out that after entering the wait () function, the thread automatically releases all of the locks it owns. So that other threads can regain these locks and use
These locks do something that allows certain conditions to be met before notifying the WAI thread.
Java Wait (), notify (), Notifyall () Understanding