10. nally{
11. 清理工作
12. }
13. }
我们看到,如果线程执行一般逻辑在调用 innterrupt 后,isInterrupted()为 true,退出循环后执行清理工作后结束,即使线程正在 wait,sleep,join,也会抛出异常执
行清理工作后退出。
这看起来非常好,线程完全按最我们设定的思路在工作。但是,并不是每个程序员都有这种认识,如果他聪明的自己处理异常会如何?事实上很多或大多数程序员会这
样处理:
1. publicvoidrun(){
2. while(!isInterrupted()){
3. try{
4. //正常工作
5. }catch(Exceptione){
6. //nothing
7. }finally{
8. }
9. }
10. }
想一想,如果一个正在 sleep 的线程,在调用 interrupt 后,会如何?wait 方法检查到 isInterrupted()
为 true,抛出异常,而你又没有处理。而一个抛出了 InterruptedException 的线程的状态马上就会被置为
非中断状态,如果 catch 语句没有处理异常,则下一次循环中 isInterrupted()为 false,线程会继续执行,
可能你 N 次抛出异常,也无法让线程停止。
那么如何能确保线程真正停止?在线程同步的时候我们有一个叫“二次惰性检测”(double check),能
在提高效率的基础上又确保线程真正中同步控制中。那么我把线程正确退出的方法称为“双重安全退出”,
即不以 isInterrupted()为循环条件。而以一个标记作为循环条件:
1. classMyThreadextendsThread{
2. privatebooleanisInterrupted=false;//这一句以后要修改
3. publicvoidinterrupt(){
4. isInterrupted=true;
5. super.interrupt();
6. }
7. publicvoidrun(){
8. while(!isInterrupted){
9. try{
10. //正常工作
11. }catch(Exceptione){