import java.util.*;
public class TestInterrupt { /**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread thread = new MyThread();
thread.start();
try{
Thread.sleep(10000);
}catch(InterruptedException e){
thread.interrupt();
}
}}
class MyThread extends Thread{
//boolean bl = true;
public void run(){
while(true){
System.out.println("========="+new Date()+"========");
try{
sleep(1000);
}catch(InterruptedException e){
return;
}
}
}
}
10秒之后不终止,一直跑,哪位高手帮解释一下呗,万分感谢,本人初学者。

解决方案 »

  1.   


    try{
     Thread.sleep(10000);
     }catch(InterruptedException e){
     thread.interrupt();
     }  我是用这个来控制 子线程的终止了吗  ? 这样不可以?
      

  2.   

    你的线程中断写到捕捉异常里面去了;由于没有异常故不能进入异常部分
    你可以这样写:
    import java.util.*;
    public class TestIter { /**
     * @param args
     */
     public static void main(String[] args) {
     // TODO Auto-generated method stub
     MyThread thread = new MyThread();
     thread.start();
     try{
     Thread.sleep(10000);
     }catch(InterruptedException e){
     e.printStackTrace();
     } }}
    class MyThread extends Thread{
     //boolean bl = true;
     public void run(){
     while(true){
     System.out.println("========="+new Date()+"========");
     try{
     sleep(1000);
     interrupt();
     }catch(InterruptedException e){
     return;
     }
     }
     }
    }
      

  3.   


    MyThread thread = new MyThread();
    thread.start();
    try{
    Thread.sleep(10000);
    }catch(InterruptedException e){
    thread.interrupt();
    }
    上面的代码应该写成下面这样
    MyThread thread = new MyThread();
    thread.start();
    try{
    Thread.sleep(10000);
    }catch(InterruptedException e){

    }//中断子线程
    thread.interrupt();
      

  4.   

    你的)
    sleep(1000);改成 sleep(10000)不就和你老师一模样
      

  5.   

    10楼的输出结果是正确的, 但是有点我不理解,难道线程的Thread.sleep(10000)没有异常吗?或者说没抛异常吗?
      

  6.   

    我只看到了你的interrupt是写在InterruptedException异常里面的不interrupt就不会抛出异常,根本不可能进入catch里面的代码块,不知道视频里面是怎么样的有点迷茫了,我也学了才不久呢