import java.util.*;
public class TestSleep

public static void main(String[] args) 
{
Run r = new Run();
Thread t = new Thread(r);
t.start();
try{Thread.sleep(10000);}
catch(InterruptedException e){
t.interrupt();
}
}
}
class Run implements Runnable
{
boolean flag = true;
public void run(){
while(flag){
try{Thread.sleep(1000);}catch(InterruptedException e){return ;}
System.out.println("------"+ new Date()+ "-----");
}
}
}

解决方案 »

  1.   

    主程序的 t.interrupt(); 放错位置了,不能放在catch中,应该移动到括号外面去。
      

  2.   

    import java.util.*;
    public class TestInterrupt {
      public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
        try {Thread.sleep(10000);}
        catch (InterruptedException e) {}
        thread.interrupt();
      }
    }class MyThread extends Thread {
    boolean flag = true;
      public void run(){
        while(flag){
          System.out.println("==="+new Date()+"===");
          try {
            sleep(1000);
          } catch (InterruptedException e) {
            return;
          }
        }
      }
    }
    那这个为什么在括号里可以实现那? 求大神详细解答下啊
      

  3.   

    主线程根本不会被interrupt,不会抛InterruptedException
      

  4.   

    什么意思啊? main里面的不会抛出异常??