I am stopping the thread execution using Thread.interrupt but the thread execution won’t stopped . It’s still running .
Example :
Thread t = new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
while(i<10000){
if(Thread.currentThread().isInterrupted()){
System.out.println("Thread Interrupted but it still running");
}
System.out.println(++i);
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
t.interrupt();
I can’t check Thread.isInterrupted() then if thread is interrupted break out of the loop . I can’t do this . Here , I am just showing the sample example .
My doubt is Thread.interrupt is only sets interrupted flag only or it really stops the execution .
any help regarding this will be appreciated.
How can I stop the thread execution or kill the running thread?
Thread.interrupt() will genuinely interrupt an operation that actually checks for that state (either, say, an interruptible I/O operation or else some user code that explicitly checks isInterrupted() as in principle you do in the code you quote).
In the specific example you quote, you need to bear in mind that:
per second;
of times per second.
In other words, your task of decrementing a counter 10,000 times is something that happens so fast that to all intents and purposes it will barely register as being an “interruptible task”. In practice, either all 10,000 decrements will happen before the other thread has chance to call interrupt() or they won’t.