Interrupt state of the thread

void mySubTask(){
try{sleep(delay)}
catch(InterruptedException e){Thread.currentThread.interrupt();}
}

this string of code is a concurrent section of "java Core Technology". 14.2 interrupt thread, 634 pages.

when a thread is in a blocking state, sending an interrupt signal to it causes an InterruptedException exception to be thrown. So why does the above code set the break state to this exception after it has been caught? In other words, what"s the point of setting the interrupt state here?

Apr.03,2021

clears the interrupt flag bit after throwing an exception, and calls Thread.currentThread.interrupt () to reset the interrupt state to let the caller know that the thread ended because of the interrupt.

for example, in your code above, sleep responds to interrupts. When a thread is in seep, if there is an interrupt request at this time, it will throw an InterruptedException exception and clear the interrupt state, so we sometimes need to reset it to interrupt state (in fact, we need to maintain this interrupt state).

public class Test {
    public static int count = 0;
    public static void main(String[] args) throws InterruptedException {
        Thread th = new Thread(){
            @Override
            public void run() {
                while(true){
                    if(Thread.currentThread().isInterrupted()){//1
                        System.out.println("Thread Interrupted");
                        break;
                    }
                    System.out.println("invoking!!!");
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        System.out.println("Interruted When Sleep");
                        //1
                        Thread.currentThread().interrupt();
                    }

                }
            }
        };
        th.start();
        Thread.currentThread().sleep(1000);
        th.interrupt();
    }
}
:
invoking!!!
Interruted When Sleep
Thread Interrupted

throwing InterruptedException in wait consumes the interrupt state of this thread

is it possible to interrupt again to pass?

Menu