简体   繁体   English

Java wait()/ notify()在同一对象中不起作用?

[英]Java wait()/notify() not working in same object?

Essentially, this is what I'm trying to do: 本质上,这就是我想要做的:

  1. A while loop is running some I/O code. while循环正在运行一些I / O代码。 It has a conditional section that executes if a volatile boolean is true. 它具有一个条件部分,如果易失布尔值为true,则执行该条件部分。 It then enters a synchronized block with a while loop. 然后,它进入带有while循环的同步块。 Standard practice. 标准做法。 It calls 'this.wait()' and waits for the notification. 它调用“ this.wait()”并等待通知。

      while((len=ais.read(buff))>=0) { source.write(buff, 0, len); if(paused) { synchronized(this) { while(paused && playing) { try { System.out.println("waiting..."); this.wait(); System.out.println("out of wait"); } catch (InterruptedException e) { e.printStackTrace(); } } } } if(!playing) break; } 
  2. Other methods in the SAME object change the boolean 'paused' to false. SAME对象中的其他方法将布尔值“ paused”更改为false。 The method then calls 'this.notify' 然后该方法调用“ this.notify”

     public void resume() { synchronized(this) { if(paused) { paused = false; this.notify(); } } } 

    The problem is when you call that method, the thread isn't waking up. 问题是当您调用该方法时,线程没有唤醒。 The "out of wait" println never even prints. “等待中”的println甚至不会打印。 Why is this? 为什么是这样? Can you not do wait/notify within the same object. 您能否在同一对象内不等待/通知。

Solved! 解决了! Completely forgot that that first part of code (the waiting part) was in a nested class and therefore wasn't the same object. 完全忘记了代码的第一部分(等待部分)在嵌套类中,因此不是同一对象。 I came to realize this when I noticed their hash codes weren't the same. 当我发现他们的哈希码不一样时,我意识到了这一点。

Are paused and playing declared as volatile? 被暂停并且播放声明为不稳定吗? It is possible that one of the threads does not see the other thread's modification of these global variables. 一个线程可能看不到另一个线程对这些全局变量的修改。 Also, we do not know anything about the value of playing. 另外,我们对比赛的价值一无所知。

只需尝试使用notifyAll() ,一切都应该没问题

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

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