我正在使用服务
开发音乐播放器应用程序。在服务中,我在新线程中处理所有 MediaPlayer
函数。这是我的类,它实现了 Runnable:
public class MusicPlayerThread implements Runnable {
boolean shouldPlayNext=false;
public void run {
while(true) {
if(shouldPlayNext) //shouldPlayNext always is false
//code to play next song
}
}
public void playNext() {
shouldPlayNext=true; //although control reaches here..
}
}
playNext()
是仅从此Thread
外部调用的方法。
所以我尝试这样做:
public void run {
while(true) {
if(getshouldPlayNext) //code to play next song
}
}
synchronized public void playNext() {
shouldPlayNext=true;
}
synchronized public boolean getshouldPlayNext() {
return shouldPlayNext;
}
尽管如此,run
方法始终将 shouldPlayNext
视为 false。我什至尝试将变量声明为:
volatile boolean 值shouldPlayNext=false;
我错过了什么?谢谢。
最佳答案
尝试
volatile boolean shouldPlayNext=false;
线程可以保留变量的缓存副本。因此,理论上,即使实际变量发生更改,线程也可以继续使用旧的缓存副本。 volatile
关键字使变量的读/写对所有线程可见。
关于java - Runnable 内的标志(Android :Thread inside Service) not updating properly?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18212571/