我想用interrupt()终止一个线程,java文档中说如果线程中有sleep()方法,会抛出一个InterruptedException异常。我的线程中有sleep()方法,我想用catch捕获这个异常,但系统报错说"unreachable catch block for InterruptedException",请大家帮忙。

解决方案 »

  1.   

    把catch(InterruptedException e)这个catch块放到catch块的最上面,也就是说异常捕获的第一个catch为InterruptedException类型。
    还是解决不了那就贴代码吧。
      

  2.   


    你把代码贴出来,下面是关于sleep()的代码:/* This class is to implement Runnable interface where method run() is defined and a child thread is created */
    class NewThread implements Runnable {
               public void run() {                                            // defining run()
                 try{
                       for(int i=5;i>0;i--) {                        // creating child thread 
                            System.out.println("Child Thread:" + i);
                            Thread.sleep(1000);                // suspending child thread
                      }
                }catch(InterruptedException e) {
                            System.out.println("Child interrupted.");
                }
                System.out.println("Exiting child thread. ");
             }
    }
    class ThreadDemo{
             public static void main(String args[]) {
    /* instantiating an object of type Thread and passing to constructor of class */
               Thread thread=new Thread(new NewThread()); 
               thread.start();                                        // start() executes run()
                try{
                      for(int i=5;i>0;i--) {                         // creating main thread 
                         System.out.println("Main Thread: " + i);
                         Thread.sleep(2000);                  // suspending main thread
                    }
              }catch(InterruptedException e) {
                         System.out.println("Main thread interrupted.");
              }
               System.out.println("Main thread exiting.");
            }
    }
    output:
    Main Thread: 5
    Child Thread:5
    Child Thread:4
    Child Thread:3
    Main Thread: 4
    Child Thread:2
    Child Thread:1
    Main Thread: 3
    Exiting child thread. 
    Main Thread: 2
    Main Thread: 1
    Main thread exiting.
      

  3.   

    interrupt()  不能够中止运行中的线程
    是用来去掉休眠方法的中断标志的
      

  4.   

    无法catch块的InterruptedException,interrupt()  不能够中止运行中的线程,只能sleep