我有一个场景,我希望线程休眠特定的时间。
Code:
public void run(){
try{
//do something
Thread.sleep(3000);
//do something after waking up
}catch(InterruptedException e){
// interrupted exception hit before the sleep time is completed.so how do i make my thread sleep for exactly 3 seconds?
}
}
现在,我如何处理我尝试运行的线程在睡眠完成之前遇到中断异常的情况?另外,线程在被中断后是否会唤醒并进入可运行状态,或者什么时候只有在进入可运行状态后流程才会进入 catch 块?
当你的线程被中断击中时,它将进入InterruptedException
捕获块。然后,您可以检查线程休眠了多少时间,并计算出还有多少时间可以休眠。最后,最好不要吞掉异常,而是恢复中断状态,以便调用堆栈上方的代码可以处理它。
public void run(){
//do something
//sleep for 3000ms (approx)
long timeToSleep = 3000;
long start, end, slept;
boolean interrupted;
while(timeToSleep > 0){
start=System.currentTimeMillis();
try{
Thread.sleep(timeToSleep);
break;
}
catch(InterruptedException e){
//work out how much more time to sleep for
end=System.currentTimeMillis();
slept=end-start;
timeToSleep-=slept;
interrupted=true
}
}
if(interrupted){
//restore interruption before exit
Thread.currentThread().interrupt();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)