The Need for Inter-thread Signaling
Through synchronization, one thread can safely change values that another thread will read. How does the second thread know that the values have changed? What if the second thread is waiting for the values to change by rereading the values every few seconds?
One not-so-good way that a thread can wait for a value to change is by using a busy/wait:
while ( getValue() != desiredValue ) {
Thread.sleep(500);
}
Such code is called a busy/wait because the thread is busy using up processor resources to continually check to see if the value has changed. To use fewer resources, the sleep time could be increased, but then the thread might not find out about the change for quite some time. On the other hand, if the sleep time is reduced, the thread will find out sooner, but will waste even more of the processor resources. In Java, there is a much better way to handle this kind of situation: the wait/notify mechanism.
有時候我們需要線程間的通訊,比如第二個線程如何知道第一個線程的某些值發生了改變?不太好的方法如上,稱之為busy/wait,通過不斷迴圈並結合Thread.sleep()測試值是否發生變化,會佔用處理器資源,並且迴圈的頻率不容易掌握,快了浪費資源,慢了降低反應速度。像這種情況,java中給出了一種更好的解決方案:wait/notify機制
The Wait/Notify Mechanism
The wait/notify mechanism allows one thread to wait for a notification from another thread that it may proceed.
Minimal Wait/Notify
At a bare minimum, you need an object to lock on and two threads to implement the wait/notify mechanism.
Imagine that there is a member variable, valueLock, that will be used for synchronization:
private Object valueLock = new Object();
The first thread comes along and executes this code fragment:
synchronized ( valueLock ) {
try {
valueLock.wait();
} catch ( InterruptedException x ) {
System.out.println(“interrupted while waiting”);