簡體   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