One, the thread communication target
1. The goal of thread communication is to enable threads to send signals to each other
2. Thread communication enables threads to wait for signals from other threads
Two, several ways
1. By sharing objects
2. Busy waiting
Thread B runs in a loop to wait for a signal (does not release the CPU)
3, Wait,notify and Notifyall
Wait causes the thread to go to sleep or non-running state, freeing up the CPU usage;
The thread must call Wait () or notify () in the synchronization block;
When a thread calls an object's Notify () method, a thread that is waiting for the object will be awakened and allowed to execute (glossing: The thread that will be awakened is random and cannot specify which thread to wake). It also provides a notifyall () method to wake all threads that are waiting for a given object;
Iii. Loss of Signal
The Notify () and Notifyall () methods do not save the method that calls them, because there is a possibility that no thread is waiting when these two methods are called. After the notification signal is discarded. Thus, if a thread calls notify () before the notified thread calls Wait (), the waiting thread will miss the signal.
In order to avoid losing signals, they must be kept in the signal class.
Four, false wake-up
It is possible for threads to wake up without calling Notify () and Notifyall (). This is called false wakeup (spurious wakeups).
To prevent false wakeup, the member variable that holds the signal is examined in a while loop, not in the IF expression. Such a while loop is called a spin lock (glossing: This is prudent, the current JVM implementation spin consumes the CPU, if the Donotify method is not called for a long time, the Dowait method will always spin and the CPU will consume too much). The awakened thread spins until the condition in the spin lock (while loop) becomes false.
V. Do not call wait () in a string constant or global object
The problem with calling Wait () and notify () in an empty string as a synchronization block (or other constant string) for a lock is that the jvm/compiler internally converts the constant string to the same object;
The corresponding unique object should be used
Java Multithreading--thread communication