import java.util.*;
public class Testxiancheng1 {
public static void main(String[] args) {
Mythread thread1 = new Mythread();
Thread t = new Thread(thread1);
t.start();
try {
Thread.sleep(10000);
}
catch(InterruptedException e) {
t.interrupt();
}

}
}
class Mythread implements Runnable {
public void run() {
while(true) {
System.out.println(new Date());
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
return;
}
}
}
}………为什么这程序会进入死循环?不是Mythread线程运行十秒后由t.interrupt方法结束吗?那为什么会死循环呢?不解!谁能详细说下?谢谢

解决方案 »

  1.   

    你程序中的t.interrupt(); 执行的条件是执行Thread.sleep(10000); 语句的时候抛出了异常,所以,只要这个语句一直都没有抛出异常的话,t.interrupt()语句就永远都得不到执行,因此线程就一直在执行(while(true)循环)
      

  2.   

    在Mythread 里 的Thread.sleep(1000); 后
    加上 throw new InterruptedException("老子故意的");这样就没问题了
      

  3.   

    1.t.interrupt(); 
    不能写在异常中,如果不抛出异常的话,就不会执行。
    2.sleep(1000); 是睡眠10S