这个等待通知线程语义的真正目的是什么? [英] What is real purpose of this wait-notify thread semantics?

查看:43
本文介绍了这个等待通知线程语义的真正目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚遇到了一些代码,它使用等待通知构造通过其他成员方法与类中定义的线程进行通信.有趣的是,在获取锁之后,同步范围内的所有线程都会在同一个锁上进行定时等待(参见下面的代码片段).稍后,在非同步范围内,线程执行其关键功能(即'//做一些有用的事情1').

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').

我对该机制目的的最佳猜测是,在其他线程调用someMethod"之前,尽量减少线程的资源消耗.专家们怎么看?如果是这种情况,有什么更好的方法可以实现这种行为?

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

推荐答案

此处所述,

wait-notify 模式用于一系列广泛的情况,其中一个线程需要告诉其他线程某个事件已经发生.这是通常用于实现线程池或生产者-消费者一个或多个特定线程需要接工作"的场景由其他线程创建(在这种情况下,发生的事件"是一个工作已经到达,供其中一个线程接收).

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

这篇关于这个等待通知线程语义的真正目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆