Right now I'm trying to make a function that increases the volume while boolean flag1 == true. So what I want to do is increase volume (I can do this), wait and do nothing ("nop"), then check the flag again.
I've tried doing a while-loop with Thread.sleep() but it gave kinda unreliable behaviour. Keep in mind I'm calling this function from within a service which may have been started more than once, so it's important that I check the flags.
Here's a sample of what I tried:
private void cycleVolume() {
while (flag1 == true) {
mAudioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
try {
Thread.sleep(750);
} catch (Inte开发者_开发百科rruptedException e) {
e.printStackTrace();
}
}
flag1 becomes false from a BroadcastReceiver event, which should stop executing this function hopefully. However in testing I noticed that this doesn't happen for quite some time after it's supposed to happen, and since I've never done much with Threads before I'm guessing there's an issue there.
So what should I be doing instead?
Thanks.
I'm not sure you're going about this the right way but here is how to fix your current code.
1) Make your flag variable volatile.
2) Provide a synchronized getter and setter method for the flag.
The problem is caused by Java's memory model. Since you have 2 threads accessing the same field you need to provide a way to synchronize their access. Right now, the 2 threads may not see each other's changes to the shared field. For a simple boolean using a volatile is probably more efficient.
Is this code running in its own Thread started from the somewhere in the Service? If you haven't created a separate Thread this is running on the processes main thread and blocking it, which might be leading to your unpredictable results.
精彩评论