Thread.interrupted在java中不起作用

时间:2014-01-22 11:58:54

标签: java thread-sleep

我在oracle Docs中读取了java,因为Thread.interrupted会将Thread恢复为非中断状态。 当线程通过调用静态方法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

1 个答案:

答案 0 :(得分:1)

我在评论中所说的部分错误。实际上Java 7 Docs sais:

  

如果在调用wait()时阻塞了这个线程,请等待(long),   或者等待(long,int)Object类或join()的方法,   join(long),join(long,int), sleep(long)或sleep(long,int),方法   这个类,然后它的中断状态将被清除   收到InterruptedException。

来源:http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#interrupt()

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

另见:http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep(long)