java - Wait() 和 NotifyAll()

标签 java multithreading

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();

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 会唤醒吗?

最佳答案

您正在等待和通知 2 个不同的对象 - 因此它们不会相互交谈。您需要使用一个公共(public)对象并对该公共(public)对象调用 waitnotifyAll 方法。

例如:

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

注意:

  • 我已将 q 设为私有(private)和最终状态,以确保引用不会被外部更改。
  • 同步块(synchronized block)的监视器现在在队列本身而不是 this 中。

关于java - Wait() 和 NotifyAll(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14709396/

相关文章:

java - 如何专门实现这个子类来绕过附加目标文件?

multithreading - 在Visual Studio Express 2010中进行调试时如何列出线程

c# - 异常记录中的空引用异常屏蔽真错误

java - 如何从正在运行的程序创建可执行文件(或 JAR)?

java - Eclipse VM 不会运行 Java 1.6

java - Codility FrogJmp奇怪的Java分数

java - 这段代码是冒泡排序的正确实现吗?

ios - 线程安全和 "Collection was mutated while being enumerated"

java - 执行器服务——不阻塞主程序

multithreading - 如何确保iocp中的线程安全接收?