0

I just came across some code which uses wait-notify construct to communicate with thread defined in a class, by its other member-methods. Amusingly, after acquiring lock, all thread does in synchronized scope is timed-wait on same lock (see below snippet). Later, in non-synchronized scope, thread executes its key function (ie '//do something useful1').

My best guess at purpose of this mechanism is, to minimize thread's resource-consumption until call to 'someMethod' is made by other thread. What do experts think? If this is the case, what are better ways of achieving this behavior?

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
    }
}
4

2 回答 2

4

As described 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).

于 2013-10-18T14:41:30.470 回答
1

获取锁后,同步范围内的所有线程都在同一锁上定时等待(见下面的代码片段)。

是的,模式很奇怪。通常我有一个类似的循环(尽管我总是使用 a private final lockObject)等待一小段时间,因为我不希望该方法旋转 - 过于频繁地执行其任务。

我原以为另一种方法会锁定同一个变量,然后更新isShuttingDown标志。但是执行其他// useful#部分是一种奇怪的模式,因为代码中存在许多竞争条件,这将使确定有用部分的顺序变得不可能。

于 2013-10-18T15:28:21.750 回答