Check if a thread is interrupted?

interrupt, java, multithreading

Solution

This is wrong, because if `sleep` finds that the thread is interrupted, it will throw an `InterruptedException` and clear the interrupted flag. You then swallow that exception, suppressing any record that the thread was ever interrupted. Instead, you should write something more like this:

public void run(){
    for(int i=1;i<=100;i++){

        System.out.println("THREAD VALUE AFTER 1 SECOND IS: "+i);

        if(i==3){
            Thread.currentThread().interrupt();
            gotoInform();
            break;
        }
        try{
            Thread.currentThread().sleep(1000);
        }
        catch(final Exception e){
            e.printStackTrace();
            if(e instanceof InterruptedException) {
                // just in case this Runnable is actually called directly,
                // rather than in a new thread, don't want to swallow the
                // flag:
                Thread.currentThread().interrupt();
            }
            return;
        }
    }
}

(Note: I'm assuming that this is not "real" code, but rather, that you're just trying to learn how thread interruption works. In "real" code, you should almost never need to interrupt the current thread in this way.)

Problem

I just want to get know about if this thread is interrupting or not if I'm doing it right? please give me hint if I'm wrong ``` public void run(){ int i; while(!Thread.currentThread().isInterrupted()){ for(i=1;i<=100;i++){ System.out.println("THREAD VALUE AFTER 1 SECOND IS: "+i); if(i==3){ Thread.currentThread().interrupt(); gotoInform(); break; } try{ Thread.currentThread().sleep(1000);////to sleep the Thread for 1 Second (1000ms) } catch(Exception e){ System.out.printf("Error"+e); } } } ```

Original source