Я читал в Oracle Docs для java, поскольку Thread.interrupted вернет поток в непрерываемый статус. Когда поток проверяет наличие прерывания, вызывая статический метод Thread.interrupted, статус прерывания сбрасывается. Нестатический метод isInterrupted, который используется одним потоком для запроса состояния прерывания другого, не изменяет флаг состояния прерывания.
Пожалуйста, дайте мне знать, что происходит, потому что,
if(Thread.currentThread().isInterrupted())
{
flag = 999;
Thread.currentThread().interrupted();
System.out.println("Interruption cleared");
}
Блок выше вообще не вызывается.
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();
}
}
}
Вывод:
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());
- person Marko Topolnik   schedule 22.01.2014