62,614
社区成员
发帖
与我相关
我的任务
分享
while(more work to do){
try{
do more work
Thread.sleep(delay);
}catch(Exception e){
// thread was interrupted during sleep
}
}
如果打断位设为true,根本走不到while中的isInterrupted方法在sleep就直接停了。所以无所谓判断isInterrupted,因为false的时候永远循环,true的时候永远走不到。
//循环结构1 try在while的外层,书中的原文所指的是这样的结构
public void run()
{
try
{ //try在while外层,因为异常是在while的外层捕获的,
//所以发生异常时就会退出while层而跳转到catch部分
. . .
while (more work to do)
{
do more work
Thread.sleep(delay); //如果发生中断,将停止sleep,同时抛出中断异常
}
}
catch(InterruptedException e)
{
// thread was interrupted during sleep //所以就会退出while循环,跳转到这里
//所以while循环的条件里加上isInterrupted判断是没有意义的,因为已经退出while循环了
}
finally
{
cleanup, if required
}
// exiting the run method terminates the thread
}
//循环结构2 try在while的内层
public void run()
{
while (!isInterrupted() && more work to do)
{ //try在while的内层,因为异常是在while内层捕获的,
//所以发生异常的时候不会退出while,而是跳转到while内层的catch部分
try
{
do more work
Thread.sleep(delay); //如果发生中断,将停止sleep,同时抛出中断异常
}
catch(InterruptedException e)
{
// thread was interrupted during sleep
//所以这里将捕获中断异常,同时清空中断标志
//所以while的isInterrupted判断将变为false,
//也就是说该判断没有意义,画蛇添足,因为达不到中断后退出循环的效果
//要想达到中断退出循环的效果,就要自己在这里加上 break 来退出while循环
}
finally
{
cleanup, if required
}
// exiting the run method terminates the thread
}
}
while(more work to do){
try{
do more work
Thread.sleep(delay);
}catch(Exception e){
// thread was interrupted during sleep
}
}