I read in oracle Docs for java as Thread.interrupted will bring back the Thread to non interrupted status. When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static isInterrupted method, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.
Please let me know whats going wrong because ,
if(Thread.currentThread().isInterrupted())
{
flag = 999;
Thread.currentThread().interrupted();
System.out.println("Interruption cleared");
}
Above block is not called at all.
public static void main(String args[])
{
int n = 5;
int flag = 1;
for (int i = 0; i < n; i++)
{
try
{
System.out.println("i:"+i+":n:"+n+":Thread.currentThread().isInterrupted():"+Thread.currentThread().isInterrupted());
Thread.sleep(2000);
if(i==(flag))
Thread.currentThread().interrupt();
}
catch(Exception e)
{
System.out.println(Thread.currentThread().isInterrupted()+"Exception :"+i);
if(Thread.currentThread().isInterrupted())
{
flag = 999;
Thread.currentThread().interrupted();
System.out.println("Interuption cleared");
}
System.out.println(Thread.currentThread().isInterrupted()+"Exception :"+i);
e.printStackTrace();
}
}
}
Output:
i:0:n:5:Thread.currentThread().isInterrupted():false
i:1:n:5:Thread.currentThread().isInterrupted():false
i:2:n:5:Thread.currentThread().isInterrupted():true
falseException :2
falseException :2
i:3:n:5:Thread.currentThread().isInterrupted():false
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at leo.threads.InterruptSleepMessages.main(InterruptSleepMessages.java:14)
i:4:n:5:Thread.currentThread().isInterrupted():false
currentThread().interrupt(); System.out.println(Thread.interrupted()); System.out.println(Thread.interrupted());- Marko Topolnik