当run方法返回或者出现了方法中没有捕获的异常,线程将终止。
Interrupt方法可以用来请求终止线程。当对一个方法使用interrupt方法时,线程的中断状态被重置。中断状态是每一个线程的boolean标志,每个线程应该不时的检查这个标志。要弄清中断状态,可以调用静态方法Thread.currentThread获取当前线程,然后调用isInterrupted方法:
While(!Thread.currentThread().isInterruted()){
…....
}
然而,当线程被阻塞(调用sleep或wait),就无法检测中断状态,从而产生Interrupted Exception。
一般情况下,线程简单地将中断作为一个终止请求。这种现成的run方法如下:
public void run(){
try{
while(!Thread.currentThread().isInterruted()&&more worl to do){
… …
}
}catch(InterruptedException e){
//Thread was interrupted during sleep or wait
}finally{
……
}
}
如果每次工作完之后就调用sleep,则isInterruted方法就没有必要也没有用,它会清除中断状态并且抛出异常。这时捕获Interrupted Exception采用如下方法:
public void run(){
try{
while(more work to do){
… …
Thread.sleep(delay);
}
}catch(InterruptedException e){
//Thread was interrupted during sleep
}finally{
……
}
}