calling Object.notify() before Object.wait()

后端 未结 4 1651
独厮守ぢ
独厮守ぢ 2021-01-06 03:46

If there is no thread which is waiting, using Object.wait() , any calls to Object.notify() or Object.notifyAll() have no effect. I hav

相关标签:
4条回答
  • 2021-01-06 04:22

    This kind of scenario seems to be a perfect fit for a Semaphore. Call Semaphore.release() instead of notify() and Semaphore.acquire() instead of wait.

    0 讨论(0)
  • 2021-01-06 04:22

    I would use Semaphore, CyclicBarrier or possibly CountDownLatch - whichever is a better fit for your real scenario. I think it's a good idea to reuse existing abstractions rather than use the low-level mechanisms yourself, unless those mechanisms give you exactly the behaviour you want (which they don't in this case).

    0 讨论(0)
  • 2021-01-06 04:22

    I implemented it like this

    Thread A:

     req.run();
    synchronized (req) {
                        try {
                            req.wait(3000);
                            rawResponse = eq.ReturnXML;
                            logger.info("[" + refID + "] Response recieved: " + rawResponse);
                            responseRecieved = true;
                            req.notify();
                        } catch (InterruptedException ex) {
                            logger.error("Error waiting on req", ex);
                        }
                    }
    

    Thread B:

    synchronized (req) {
            while (!responseRecieved) {
                try {
                    req.wait(3000);
                } catch (InterruptedException ex) {
                    logger.error("Error waiting on req while trying to get state", ex);
                }
            }
        }
    

    Thread A makes the request and waits for a response, in the meanwhile Thread B is only waiting for the response. If a response has already arrived it does not wait.

    0 讨论(0)
  • 2021-01-06 04:33

    Use a flag to indicating a notification. Read the flag before entering wait and act accordingly.

    boolean stopped = false;
    
    public void run(){
       synchronized(object){
          while(!stopped)
            object.wait();
       }
    
    }
    
    public void stop(){
      synchronized(object){
        stopped=true;
        object.notify();
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题