一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Java Thread Programming 1.8.1 - Inter-thread Commu

时间:2008-01-12 编辑:简简单单 来源:一聚教程网

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”);

热门栏目