简体   繁体   English

Thread.interrupt 返回 false

[英]Thread.interrupt is returing false

I was trying out the below code, I interrupted a user thread, when I print the value of isInterrupted it is returning false, I didn't got a single true value, over here the flag will get reset when the exception has been caught or on calling interrupted method.我正在尝试下面的代码,我中断了一个用户线程,当我打印 isInterrupted 的值时,它返回 false,我没有得到一个真正的值,这里的标志将在捕获异常时重置或在调用中断方法时。

Secondly, as per my understanding sleep method should throw and interruptedException in each iteration, the value in catch print, but it is throwing only once.其次,根据我的理解 sleep 方法应该在每次迭代中抛出和中断异常,catch 打印中的值,但它只抛出一次。


class ThreadInterruptt extends Thread
{
    public void run()
    {

        for(int i = 0; i<100;i++)
        {
            try {
                Thread.sleep(1000);
                System.out.println(i);
                System.out.println(isInterrupted());
            } catch (InterruptedException e) {
                System.out.println("Thread Interrupted");
            }
        }
    }
}
public class ThreadInterrupt {
    public static void main(String ag[]) throws InterruptedException
    {
        ThreadInterruptt t = new ThreadInterruptt();
        t.start();
        Thread.sleep(100);
        t.interrupt();

    }

}

You wouldn't ever get to the isInterrupted() check if you are interrupted: Thread.sleep() would have thrown an exception, and also it clears the interrupted status of the Thread, as described in the Javadoc .如果您被中断,您将永远不会进行isInterrupted()检查: Thread.sleep()会抛出异常,并且它还会清除 Thread 的中断状态, 如 Javadoc 中所述

And you're then discarding the fact the thread was interrupted (because you don't reset the interrupted flag on catching the exception), so it's not interrupted on the next iteration.然后您放弃了线程被中断的事实(因为您没有在捕获异常时重置中断标志),因此它不会在下一次迭代中被中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM