while循环中的异常vs isInterrupted [英] Interrupted exception vs isInterrupted in a while loop

查看:401
本文介绍了while循环中的异常vs isInterrupted的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码:

while(!Thread.currentThread().isInterrupted()){  
    //do something   
    Thread.sleep(5000);  
}

现在 Thread.sleep 抛出`InterruptedException所以它应该是这样的:

Now Thread.sleep throws `InterruptedException so it should be like this:

while(!Thread.currentThread().isInterrupted()){  
   //do something   
   try{  
     Thread.sleep(5000);    
   } catch(InterruptedException e){  

   }
}

如果我点击 catch 循环继续或我是否需要 Thread.currentThread()。中断()?如果我确实调用了这个方法,那么这也不会导致 InterruptedException 吗?否则我是如何得到例外的?

If I hit the catch will the while loop continue or do I need to do Thread.currentThread().interrupt()? If I do call this method, won't that also cause an InterruptedException? Otherwise how I got the exception in the first place?

如果我有:

while (!Thread.currentThread().isInterrupted()){  
   //do something   
   callMethod();  
}  

private void callMethod(){  
   //do something  
   try {  
     Thread.sleep(5000);    
   } catch(InterruptedException e){  

   }
}

我的再次循环中断?

推荐答案

实际上你的问题更多的是关于 try - catch - finally 而不是关于多线程。

Actually your question is more about try - catch - finally than about multithreading.

1)如果 sleep 抛出异常,执行 catch 块,然后执行 while 循环继续。

1) If sleep throws an Exception, the catch block will execute and then the while loop continues.

2)你做的完全相同于1)

2) You do the exact same thing as in 1)

要在循环时离开,请执行:

To leave the while loop, do:

try{  
   while(!Thread.currentThread.isInterrupted){  
       //do something   
       Thread.sleep(5000);    
   }  
}
catch(InterruptedException e){  

}

在这种情况下,如果抛出异常,则会留下循环,执行 catch 块。

In that case, if an Exception is thrown, the while loop is left and the catch block is executed.

这篇关于while循环中的异常vs isInterrupted的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆