java - Why we use a flag to stop a thread? -
when tried figure out how stop thread in program multiple threads,
suggested call method sets flag tell 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 real work ,like counting..."); for(int i=0;i<100;i++){} } catch (interruptedexception e) { logger.error("exception", e); running = false; } } } }
when want stop tread ,i'll call threadinstance.terminate();
.
don't need literally stop thread ?
why should leave thread useless work (method run
called ,test flag running==false
return)? mean :this waste of time ,isn't it?
when execution scope goes beyond run()
method, thread stops, moment while
loop broken, thread stop.
this allow clean if situation requires it:
public void run() { while (running) { try { logger.debug("doing real work ,like counting..."); for(int i=0;i<100;i++){} } catch (interruptedexception e) { logger.error("exception", e); running = false; } } //clean }
the above approach allows control on how thread stops and happens after opposed potentially kill it, cause kinds of problems.
Comments
Post a Comment