| ||||
Copyright 1999 Sams Publishing |
|
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. |
| |||
Toc |