I have a Runnable class which performs an operation continuously in its run method using an infinite while loop. Sometimes a user might want to pause/resume the operation. What is the best method to pause the Thread. I have two thoughts:
FIRST
class Foo extends Runnable {
@Override
public void run() {
while(true) {
if(pauseFlag)
try{
Thread.sleep();
} catch(InterrruptedException ie) {//...}
}
}
SECOND
class Foo extends Runnable {
@Override
public void run() {
while(true) {
//pause if user wants to pause
while(pauseFlag);
}
}
}
Because it has nothing to do with synchronization, i do not want to use wait/notify.
Because it has nothing to do with synchronization, i do not want to use wait/notify.
It has everything to do with synchronization. Presumably your user interaction occurs on a different thread - so you're trying to synchronize signals between the two threads.
You shouldn't use Thread.sleep
or a tight loop here. Either wait
/notify
or something similar using a higher-level construct in java.util.concurrent
is the right approach here.
Note that without any memory barriers, changes to your pauseFlag
from one thread may not be noticed in a different thread, so you'd at least want to make it volatile.
See more on this question at Stackoverflow