She*_*lly 0 java concurrency multithreading java-threads
我正在尝试下面的代码,我中断了一个用户线程,当我打印 isInterrupted 的值时,它返回 false,我没有得到一个 true 值,在这里,当捕获异常时,标志将被重置或关于调用被中断的方法。
其次,根据我的理解,sleep方法应该在每次迭代中抛出和interruptedException,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();
}
}
Run Code Online (Sandbox Code Playgroud)
isInterrupted()
如果您被中断,您将永远无法进行检查:Thread.sleep()
会抛出异常,并且它还会清除线程的中断状态,如 Javadoc 中所述。
然后您将丢弃线程被中断的事实(因为您在捕获异常时没有重置中断标志),因此它在下一次迭代中不会被中断。
归档时间: |
|
查看次数: |
105 次 |
最近记录: |