Thread.interrupted在java中不工作

Thread.interrupted在java中不工作,java,thread-sleep,Java,Thread Sleep,我在OracleDocsforJava中读到Thread.interrupted会将线程恢复为非中断状态。 当线程通过调用静态方法thread.interrupted检查中断时,中断状态被清除。一个线程用来查询另一个线程的中断状态的非静态isInterrupted方法不会更改中断状态标志 请告诉我出了什么问题,因为 if(Thread.currentThread().isInterrupted()) { flag =

我在OracleDocsforJava中读到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();
        }

    }
}

我在评论中所说的部分是错误的。实际上,Java 7文档SAI:

如果该线程在wait()的调用中被阻塞,wait(long), 或对象类或join()的wait(long,int)方法, join(long)、join(long,int)、sleep(long)或sleep(long,int)方法 则其中断状态将被清除,并且 接收中断异常

资料来源:

因此,抛出的InterruptedException清除状态,而不是捕获状态。 看到的效果是一样的。当i=1时,标志由
interrupt()
设置,执行
sleep
将清除标志并引发异常,从而产生可见的输出


另请参见:

您编写了一段非常复杂的代码,好像您的目标是迷惑自己。为什么不试试简单的东西呢<代码>当前线程().中断();System.out.println(Thread.interrupted());System.out.println(Thread.interrupted())记住:捕获中断异常也会清除状态。您捕获了异常,因此当i=2时,Thread.sleep也会抛出InterruptedException。然后状态被catch清除,if条件为false。所以它确实工作得很好。@Fildor好的,我知道异常也会清除线程的中断状态。谢谢你的解释。它很有用。你可能想接受这个问题的答案?抱歉@Fildor太晚了。谢谢你的回答
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