gpt4 book ai didi

java - notifyAll() 不起作用

转载 作者:行者123 更新时间:2023-11-30 06:58:38 26 4
gpt4 key购买 nike

在下面的代码中调用了 notifyAll() 但没有重新激活其他线程。我得到的输出是

  • beta 等待通知时间:1441870698303,activeWriters:1

  • alpha 等待通知时间:1441870698303,activeWriters:1

  • 增量通知时间:1441870698403,activeWriters:0

    公共(public)类 Waiter 实现 Runnable{

        private static int activeWriters;

    public Waiter(Message msg){
    }

    @Override
    public void run() {
    beforeWrite();
    try {
    Thread.sleep(100);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    afterWrite();
    }

    protected synchronized void beforeWrite(){
    while (activeWriters > 0 ) {
    try {
    System.out.println(Thread.currentThread().getName() +" waiting to get notified at time: "+System.currentTimeMillis()+ ", activeWriters: " + activeWriters);
    wait();
    System.out.println(Thread.currentThread().getName() +" waiting got notified at time: "+System.currentTimeMillis()+ ", activeWriters: " + activeWriters);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    ++activeWriters;
    }
    protected synchronized void afterWrite(){
    --activeWriters;
    System.out.println(Thread.currentThread().getName() +" notify all at time: "+System.currentTimeMillis() + ", activeWriters: " + activeWriters);
    notifyAll();
    }

    }

    public class WaitNotifyTest {

    public static void main(String[] args) {
    Message msg = new Message("process it");
    Waiter waiter1 = new Waiter(msg);
    Waiter waiter2 = new Waiter(msg);
    Waiter waiter3 = new Waiter(msg);
    new Thread(waiter1,"alpha").start();
    new Thread(waiter2, "beta").start();
    new Thread(waiter3, "delta").start();

    }

    }

最佳答案

调用 wait()notify*() 作用于指定的对象,这意味着 notify*() 唤醒线程在同一个对象上调用了 wait()

在您的情况下,您在 3 个未连接的不同对象上调用了 wait()notifyAll(),因此这是行不通的。

你可以添加一个静态互斥量:

private static final Object mutex = new Object();

然后对该对象调用wait()notify*()。请记住首先在互斥量上同步:

synchronized (mutex) {
...
mutex.wait();
...
}

和:

synchronized (mutex) {
...
mutex.notifyAll();
...
}

所有对 activeWriters 的访问都必须在这些 synchronized block 中进行,原因有两个。目前对它的访问实际上是不同步的,因为您在 3 个不同的对象上同步。除此之外,activeWriters 是您的条件变量,并且您希望 notify*() 其他线程发生更改。为此,变量的更改和 notify*() 调用必须在同一个 synchronized block 中。

关于java - notifyAll() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32496098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com