In the code below, I have a while(true) loop. Consider a situation where there is some code in the try block where the thread is supposed to perform some tasks which takes about a minute, but due to some expected problem, it is running for ever. Can we stop that thread?
public class thread1 implements Runnable {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
thread1 t1 = new thread1();
t1.run();
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try{
Thread.sleep(10);
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
First of all, you are not starting any thread here! You should create a new thread and pass your confusingly named
thread1Runnableto it:Now, when you really have a thread, there is a built in feature to interrupt running threads, called…
interrupt():However, setting this flag alone does nothing, you have to handle this in your running thread:
Two things to note:
whileloop will now end when threadisInterrupted(). But if the thread is interrupted during sleep, JVM is so kind it will inform you about by throwingInterruptedExceptionout ofsleep(). Catch it and break your loop. That’s it!As for other suggestions:
AtomicBooleanorvolatile!), but why bother if JDK already provides you a built-in flag like this? The added benefit is interruptingsleeps, making thread interruption more responsive.