首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Wait()和NotifyAll()

Wait()和NotifyAll()
EN

Stack Overflow用户
提问于 2013-02-05 22:07:21
回答 1查看 132关注 0票数 1
代码语言:javascript
复制
class SimpleConsumer extends Threads {
        public SyncQueue q;
        SimpleConsumer(SyncQueue q) { this.q = q; }
        public void run () { doit(); }
        public synchronized void doit() {
            while(true){
                try{
                    while(q.isEmpty()) { wait(); }
                    System.out.println((String)q.Dequeue());
                } 
                catch (Exception e) { System.out.println("Got exception:" +e); }
            }
        }    
    }

我还有另一个类,它将项目添加到同一个对象SyncQueue中,并执行notifyAll();

代码语言:javascript
复制
class SimpleProducer extends Threads {
public SyncQueue q;
SimpleProducer(SyncQueue q) { this.q = q; }
public void run() { doit(); }
public synchronized void doit() {
    while(true){
        try{
            sleep(1000);
            q.Enqueue("Item");
            notifyAll();
            } catch(Exception e) { System.out.println("Got exception:" +e); }
        }
    }
}
} 

如果我从不同的类方法执行notifyAll(),SimpleConsumer会被唤醒吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-05 22:11:58

您正在等待并通知两个不同的对象--这样它们就不会相互通信。您需要使用一个公共对象,并对该公共对象调用waitnotifyAll方法。

例如:

代码语言:javascript
复制
class SimpleConsumer extends Threads {
    private final SyncQueue q;

    SimpleConsumer(SyncQueue q) {
        this.q = q;
    }

    public void doit() {
        while(true){
            try{
                synchronized(q) {
                    while(q.isEmpty()) { q.wait(); }
                    System.out.println((String)q.Dequeue());
                }
            } 
            catch (Exception e) { System.out.println("Got exception:" +e); }
        }
    }    
}

注意:

现在是队列本身而不是this.,我已经将

  • 设置为qq,以确保引用不会更改为同步块的监视器
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14709396

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档