How the main thread sleep/interrupt works in following code

Arasn :

How the second loop actually interrupts the sleeping main thread, and first does not?? My understanding is after Thread.sleep(3000), the code Thread.currentThread().interrupt() will be executed after 3 seconds. Can anyone explain how it actually works

for (int i = 0; i < 2; i++) {
            try {
                System.out.println("loop : " + i);
                Thread.sleep(3000);
                System.out.println("Woke up");
                Thread.currentThread().interrupt();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
loop : 0
Woke up
loop : 1
java.lang.InterruptedException: sleep interrupted
exception loop:1
    at java.base/java.lang.Thread.sleep(Native Method)
    at multithreadings.Mainclass.main(Mainclass.java:13)

Andy Turner :

Interruption is a polite request to stop: a Thread is under no obligation to stop.

It's like the Robin Williams joke about what police in the UK say when you commit a crime:

Stop! Or I'll say stop again!

Also, interrupting a thread doesn't cause an InterruptedException to be thrown: it merely sets a flag on the thread. If something (like Thread.sleep) checks this flag, and finds that it is set, it may then throw an InterruptedException; but the flag and exception are two orthogonal ways of indicating interruption.

As such:

  • On the first execution, you sleep for 3 seconds, then set the interrupted flag, and the loop body finishes normally.
  • On the second execution, you ask to sleep for 3 seconds, but Thread.sleep detects the interrupted flag, and throws the exception.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=309742&siteId=1