2

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).

Branex
  • 362
  • 1
  • 6
  • 14
  • Is `MyTask` the only task that is scheduled on this executor or do you reuse the executor to schedule other tasks as well? – cyon Dec 11 '14 at 15:05
  • The executor is running other threads as well. I just edited the last part of the question, indicating that I'd like to stop the thread without interrupting it if the interrupt condition happens when the thread is executing. – Branex Dec 11 '14 at 15:29

0 Answers0