I have a class implementing Runnable interface with run() defined as follows:
class MyTask implements Runnable {
// ...
// active is a boolean flag set to true at the beginning,
// but which can be set to false from outside of the task
// ...
@Override
public void run() {
if (active) {
// Do something
}
}
}
I add it to ScheduledExecutorService to run periodically:
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
executor.scheduleAtFixedRate(new MyTask(), 10, 10, TimeUnit.SECONDS);
When a certain condition is satisfied, I set 'active' to false and the code within the if block does not execute any more and that is good. But is that really all I need to do? If I understand this correctly, the run function will keep on getting called because the thread never dies. I'd like to make sure that this thread simply stops, and that it stops in a way that it does not get interrupted if the condition that is supposed to stop the thread comes while the thread is executing (in that case, the thread should finish the job without interruption, but never repeat again).