0

When I tried to figure out how to stop a thread in a program with multiple threads,
I was suggested to call a method which actually sets a flag to tell that thread stop doing real works,like this:

public class ThreadTobeTerminated implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
    private volatile boolean running = true;

    public void terminate() {
        running = false;
    }

    @Override
    public void run() {
        while (running) {
            try {
                LOGGER.debug("Doing some real work ,like Counting...");
                for(int i=0;i<100;i++){}

            } catch (InterruptedException e) {
                LOGGER.error("Exception", e);
                running = false;
            }
        }

    }
}

when I want to stop this tread ,I'll call threadInstance.terminate();.

Don't I need to literally stop this thread ?

Why I should leave this thread to do some useless work (method run called ,test the flag running==false then return)? I mean :this is a waste of time ,isn't it?

Community
  • 1
  • 1
wangkaibule
  • 808
  • 1
  • 9
  • 20
  • 1
    What do you propose as an alternative, that still allows the thread to stop in a *controlled* manner, instead of potentially half-way through an operation, leaving the system in a less well-defined state? – Jon Skeet Apr 01 '15 at 13:56

1 Answers1

1

When the execution scope goes beyond the run() method, the thread stops, so the moment that the while loop is broken, the thread will stop.

This would also allow you to do some clean up if the situation requires it:

public void run() {
    while (running) {
        try {
            LOGGER.debug("Doing some real work ,like Counting...");
            for(int i=0;i<100;i++){}

        } catch (InterruptedException e) {
            LOGGER.error("Exception", e);
            running = false;
        }           
    }
    //Clean up
}

The above approach allows you some control over how is the thread stops and what happens after as opposed to potentially just kill it, which could cause all kinds of problems.

npinti
  • 51,780
  • 5
  • 72
  • 96