繁体   English   中英

Java等待特定间隔通知不起作用

[英]Java wait specific interval notify not working

程式码片段:

class Counter implements Runnable {
    Object s = new Object();

    @Override
    public void run() {
        try {
            synchronized (s) {
                s.wait(10000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //...do Something
    }

    public void stopCounter() {
        synchronized (s) {
            s.notifyAll();
        }   
    }
}

无论我是否调用stopCounter,... do Something代码始终仅在等待间隔之后执行。 即使发出通知,它仍要等待10秒。

我不能从您的例子中看出您要达到的目标。 如果要尝试替换某种轮询,请考虑Java 5中发布的BlockingQueue接口。自从出现这种情况以来,我就不需要等待/通知了。 它使用起来简单得多,而且幕后的Java等效于您的wait / notify。

这取决于您使用它的方式。 我刚刚通过添加一个主要方法并运行它来进行尝试,似乎wait / notify机制运行良好,而不是您描述的方式。 请自己尝试:

public static void main(String[] args) {
  Counter c = new Counter();
  new Thread(c).start();
  try {
    Thread.sleep(1000);
  } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
  c.stopCounter();
}

我的猜测是您在Counter类的不同实例上调用runstopCounter方法。 因此,他们使用不同的监视器(您的s = new Object() ),并且stop的调用不会通知其他Counter。

例如,这与您描述的行为类似(除非您收到虚假的唤醒):

public static void main(String[] args) throws InterruptedException {
    Counter c = new Counter();
    new Thread(c).start();
    Thread.sleep(200);
    new Counter().stopCounter();
}

static class Counter implements Runnable {

    Object s = new Object();

    @Override
    public void run() {
        try {
            System.out.println("in");
            synchronized (s) {
                s.wait(10000);
            }
            System.out.println("out");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //...do Something
    }

    public void stopCounter() {
        synchronized (s) {
            s.notifyAll();
        }
        System.out.println("notified");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM