amitakCs amitakCs - 4 months ago 13
Java Question

why Thread.currentThread.interrupt() combined with return can stop a current running thread

Well, I am trying to understand why the following combination of Thread.currentThread.interrupt() and return is working fine, when I want to terminate a current thread.

Thread.currentThread.interrupt();
return;


I write a small program:

public class Interr implements Runnable {
@Override
public void run() {
for(int i= 0; i<10000;i++){
System.out.println(i);
if(i==500){
Thread.currentThread().interrupt();
return ;
}
}

}
public static void main(String args []){
Thread thread = new Thread(new Interr());
thread.run();
}
}


I know I can also use Thread.currentThread.stop() but it is an unsafe way to terminate a thread. So I tried to use the combination interupt() and return.

It works but I do not undestand why it works.

Any Explanation?

Edit: in the above example, I am the owner of a Thread. Assume, I am not the owner of a thread. Why This combination is working?

Answer

No need to call interrupt() from same thread.

interrupt method will be used to interrupt a thread from other thread.

as per java docs.

Interrupts this thread. Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.

If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.

If none of the previous conditions hold then this thread's interrupt status will be set.

Interrupting a thread that is not alive need not have any effect.

So it will send interrupt signal to the thread which is in I/O block.

@Override
public void run() {

    while (true) {

    }
}

if a thread has implementation like that , it wont interrupt even after calling this method.