简体   繁体   English

为什么notifyAll()不起作用?

[英]Why notifyAll() doesn't work?

After been thinking about a solution, i don't know why this code doesn't works properly. 在考虑解决方案之后,我不知道为什么这段代码无法正常工作。

If I execute mediaPlayer.start() , the thread enters on loop and wait() , but then, when mediaPlayer calls OnCompletionListener , notifyAll() doesn't wake from wait() , and loops in wait() state forever... 如果我执行mediaPlayer.start() ,则线程进入循环并进入wait() ,但是当mediaPlayer调用OnCompletionListenernotifyAll()不会从wait()唤醒,并且永远以wait()状态循环...

(Supposing that 'Music Thread' is properly started at the start of the class, and the same with MediaPlayer object) (假设“音乐线程”已在类的开头正确启动,并且与MediaPlayer对象相同)

private synchronized void set()
{
    while(mediaPlayer.isPlaying())
{
    try {     
        wait();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
    //DO SOMETHING (THE PROBLEM IS THAT NEVER REACHES THIS CODE)
}




private synchronized void reproductor()
{
    mediaPlayer.start();
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public synchronized void onCompletion(MediaPlayer mediaPlayer) {
            notifyAll();   //because mediaPlayer.isPlaying() changes

        }
    });
}



private class Music implements Runnable
{
    @Override
    public void run() {
        try {
            reproductor();
            while(true) {
                set();
                Thread.sleep(500);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

On the other hand, if i use contrary statement in loop it works properly ( !mediaPlayer.isPlaying() ), why? 另一方面,如果我在循环中使用相反的语句,则它可以正常工作( !mediaPlayer.isPlaying() ),为什么?

You aren't notifying the same object you're waiting on. 您没有通知正在等待的对象。 You're notifying the listener object, which is an instance of an anonymous class implementing the listener interface. 您要通知侦听器对象,该对象是实现侦听器接口的匿名类的实例。 You need to qualify notifyAll() as XXX.this.notifyAll() , where XXX is the same of the class enclosing the set() and reproductor() methods. 您需要将notifyAll()限定为XXX.this.notifyAll() ,其中XXX与包含set()reproductor()方法的类相同。

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

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