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”);
}
}
The wait() method requires the calling thread to have previously acquired the object-level lock on the target object. In this case, the object that will be waited upon is valueLock, and two lines before the valueLock.wait() statement is the synchronized(valueLock) statement. The thread that invokes the wait() method releases the object-level lock and goes to sleep until notified or interrupted. If the waiting thread is interrupted, it competes with the other threads to reacquire the object-level lock and throws an InterruptedException from within wait(). If the waiting thread is notified, it competes with the other threads to reacquire the object-level lock and then returns from wait().
Wait()方法需要在获得object-level lock之后才能调用,否则会抛出IllegalMonitor-
StateException异常,当线程调用wait()方法后,会释放object-level lock,然后sleep(),直到被notified或interrupted,如果被interrupted,此线程会重新竞争获得object-level lock,然后抛出InterrruptedException,如果被notified,此线程会重新竞争获得object-level lock,从wait()返回,继续执行wait()以后的代码。
Many times, a thread is interrupted to signal it that it should clean up and die (see Chapter 5). The statements used to wait can be slightly rearranged to allow the InterruptedException to propagate up further:
try {
synchronized ( valueLock ) {
valueLock.wait();
}
} catch ( InterruptedException x ) {
System.out.println(“interrupted while waiting”);
// clean up, and allow thread to return from run()
}
有时候,中断一个线程是为了将其销毁清除,可以将InterruptedException异常延迟处理
Instead of catching InterruptedException, methods can simply declare that they throw it to pass the exception further up the call chain:
public void someMethod() throws InterruptedException {
// ...
synchronized ( valueLock ) {
valueLock.wait();
}
// ...
}
如果不在方法内捕捉异常,可以继续上抛,留待以后处理
The thread doing the notification comes along and executes this code fragment:
synchronized ( valueLock ) {
valueLock.notify(); // notifyAll() might be safer...
}
This thread blocks until it can get exclusive Access to the object-level lock for valueLock. After the lock is acquired, this thread notifies
one of the waiting threads. If no threads are waiting, the notification effectively does nothing. If more than one thread is waiting on valueLock, the thread scheduler arbitrarily chooses
one to receive the notification. The other waiting threads are not notified and continue to wait. To notify
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有