java - 这个等待通知线程语义的真正目的是什么?

标签 java multithreading

我刚刚遇到一些代码,这些代码使用 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/

相关文章:

Android:将消息发布到 HandlerThread 会使 UI 线程无响应或给出 IllegalStateException

java - Quartz+Hibernate : simple util eats memory. 有什么问题吗?

C Windows 多线程 TCPIP 之间的连接

java - 如何从 glassfish 服务器发送邮件?

java - 如何获取 Json 对象并将其存储在 Hashmap 中

java - Spring Kafka - 代理重新连接事件

c# - Windows 窗体中的 Gif

java - 让线程返回值的正确方法是什么?

java - 如何使用节点在链表中显示字符串

java - 如果从最近使用的应用程序中删除应用程序,Android Oreo 接收器将停止