我刚刚遇到一些代码,这些代码使用 wait-notify 构造通过其其他成员方法与类中定义的线程进行通信。 有趣的是,获取锁后,同步范围内的所有线程都会在同一锁上进行定时等待(请参见下面的代码片段)。稍后,在非同步作用域中,线程执行其关键函数(即'//do some important1')。
我对此机制的目的的最佳猜测是,最大限度地减少线程的资源消耗,直到其他线程调用“someMethod”。专家有何看法?如果是这种情况,实现这种行为的更好方法是什么?
class SomeClass{
public void run() {
while (!isShuttingDown){
try {
synchronized (SomeClass.class) {
SomeClass.class.wait(500);
}
} catch (Throwable e) {
LOGGER.info(SomeClass.class.getSimpleName() + " reaper thread interrupted", e);
}
//do something useful1
}
}
public synchronized void someMethod(){
//do something useful2
synchronized (SomeClass.class) {
SomeClass.class.notifyAll();
}
//do something useful3
}
}
最佳答案
如上所述here ,
The wait-notify pattern is used in a broad set of cases where one thread needs to tell other threads that some event has occurred. It is commonly used to implement a thread pool or producer-consumer scenario, where a particular thread or threads need to "pick up jobs" created by other threads (in this case, the "event" that has occurred is that a job has arrived for one of the threads to pick up).
关于java - 这个等待通知线程语义的真正目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19452301/