我正在尝试下面的代码,我中断了一个用户线程,当我打印isInterrupted的值时,它返回false,我没有得到一个TRUE值,在这里,当异常被捕获或调用中断的方法时,标志将被重置。
其次,根据我的理解,睡眠方法应该在每次迭代中抛出和interruptedException,这个值在catch print中,但它只抛出一次。
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();
}
}发布于 2020-03-31 00:22:22
如果你被中断了,你永远不会得到isInterrupted()检查:Thread.sleep()会抛出一个异常,而且它还会清除线程as described in the Javadoc的中断状态。
然后丢弃线程被中断的事实(因为在捕获异常时不重置中断标志),这样它就不会在下一次迭代中被中断。
https://stackoverflow.com/questions/60934816
复制相似问题