Why does the InterruptedException exception sometimes work, because Thread.interrupted () checks the interrupt flag and immediately resets it?

public class TestClass { public static void main(String[] args) throws InterruptedException { Thread threadExample = new Thread(new JoinClass()); threadExample.start(); Thread.sleep(1000); threadExample.interrupt(); } } class JoinClass implements Runnable { @Override public void run() { System.out.println("run.." + Thread.currentThread().isInterrupted()); while (!Thread.interrupted()); System.out.println("end while.." + Thread.currentThread().isInterrupted()); try { Thread.sleep(100); System.out.println("try.."); } catch (InterruptedException e) { System.out.println("catch.."); } System.out.println("end run.." + Thread.currentThread().isInterrupted()); } } 

 run..false end while..false catch..false end run..false 
  • And this is what threadExample.interrupt(); ? - Sergey
  • Set the interrupt flag to true, in a thread in a while loop (! Thread.interrupted ()); check it and reset false. then we exit the loop and sleep (100). Why does sleep react to a flag, because is it already false? - Andrey
  • catch..false output of catch..false exactly from this example? Where does false come from if System.out.println("catch.."); ? - Sergey
  • of this, a bit of code has been edited. The exception does not always fly, and that's why the question is? - Andrey
  • The code above cannot throw InterruptedException() . Apparently it is not slightly edited . - Yuri Heiko

0