Java: for循环即使在当前线程中断后也执行一次
Java: for loop executes once even after interruption of current thread
我是线程概念的新手。我试图中断 运行().
中的当前线程
基本上,我试图打印出一个单词 5 次(在 for 循环中),中间有 2s sleep。当我试图在第二次循环执行之前中断线程时,我仍然在第二次打印出这个词。
public void run()
{
try{
for(int i=0;i<=5;i++){
//print word
System.out.println(word);
//sleep
Thread.sleep(2000);
//interrupt
Thread.currentThread().interrupt();
}
} catch(InterruptedException e){
System.out.println("sleep interrupted");
}
}
但是,当我编译 运行 代码时,我得到以下结果:
word
word
sleep interrupted
我原以为这个词只打印一次,因为在循环到 for 循环的下一个实例之前调用了中断。我不明白为什么第二个词和 InterruptedException "sleep interrupted" 被同时抛出..
我期待中断抛出 "sleep interrupted" 而没有第二次打印这个词。
谢谢!
- 第一次打印单词
- 睡了 2 秒
- 调用中断()
- 第二次打印字
- 调用睡眠抛出 InterruptedException
你要的是
for(int i = 0; i <= 5 && !Thread.currentThread().isInterrupted(); i++){
当您调用 Thread.currentThread().interrupt() 时,您设置线程的中断标志,然后更高级别的中断处理程序可以适当地使用它。通常,人们在捕获 InterruptedException 时使用它,即在 catch 块内让调用者知道中断已经发生。
但是在这里,您使用它来退出 for 循环。当你第二次输入 Thread.Sleep() 时,程序会实现标志设置。要手动阅读,
试试这个
for(int i=0;i<=5 && !Thread.currentThread().isInterrupted();i++)
原因是您在调用 interrupt()
时实际上并没有中断您的线程。
因此,当状态已设置为中断时,您的异常会在中断后的 秒 上触发。在这个状态下,你是不允许睡觉的,所以你得到了异常。
阅读 interrupt()
的 javadoc:
If this thread is blocked [...]
If this thread is blocked [...]
If this thread is blocked [...]
If none of the previous conditions hold then this thread's interrupt status will be set.
由于您的线程在您调用 interrupt()
时未被阻塞,它只是设置状态,而不会抛出异常。
然后sleep()
方法检测中断状态并抛出异常。
我是线程概念的新手。我试图中断 运行().
中的当前线程基本上,我试图打印出一个单词 5 次(在 for 循环中),中间有 2s sleep。当我试图在第二次循环执行之前中断线程时,我仍然在第二次打印出这个词。
public void run()
{
try{
for(int i=0;i<=5;i++){
//print word
System.out.println(word);
//sleep
Thread.sleep(2000);
//interrupt
Thread.currentThread().interrupt();
}
} catch(InterruptedException e){
System.out.println("sleep interrupted");
}
}
但是,当我编译 运行 代码时,我得到以下结果:
word
word
sleep interrupted
我原以为这个词只打印一次,因为在循环到 for 循环的下一个实例之前调用了中断。我不明白为什么第二个词和 InterruptedException "sleep interrupted" 被同时抛出..
我期待中断抛出 "sleep interrupted" 而没有第二次打印这个词。
谢谢!
- 第一次打印单词
- 睡了 2 秒
- 调用中断()
- 第二次打印字
- 调用睡眠抛出 InterruptedException
你要的是
for(int i = 0; i <= 5 && !Thread.currentThread().isInterrupted(); i++){
当您调用 Thread.currentThread().interrupt() 时,您设置线程的中断标志,然后更高级别的中断处理程序可以适当地使用它。通常,人们在捕获 InterruptedException 时使用它,即在 catch 块内让调用者知道中断已经发生。
但是在这里,您使用它来退出 for 循环。当你第二次输入 Thread.Sleep() 时,程序会实现标志设置。要手动阅读,
试试这个
for(int i=0;i<=5 && !Thread.currentThread().isInterrupted();i++)
原因是您在调用 interrupt()
时实际上并没有中断您的线程。
因此,当状态已设置为中断时,您的异常会在中断后的 秒 上触发。在这个状态下,你是不允许睡觉的,所以你得到了异常。
阅读 interrupt()
的 javadoc:
If this thread is blocked [...]
If this thread is blocked [...]
If this thread is blocked [...]
If none of the previous conditions hold then this thread's interrupt status will be set.
由于您的线程在您调用 interrupt()
时未被阻塞,它只是设置状态,而不会抛出异常。
然后sleep()
方法检测中断状态并抛出异常。