检查线程是否中断?

Jun*_*san 2 java multithreading interrupt

我只是想知道这个线程是否正在中断,如果我做得对吗?如果我错了,请告诉我

public void run(){
  int i;
  while(!Thread.currentThread().isInterrupted()){
    for(i=1;i<=100;i++){

      System.out.println("THREAD VALUE AFTER 1 SECOND IS: "+i);

      if(i==3){
        Thread.currentThread().interrupt();
        gotoInform();
        break;
      }
      try{
        Thread.currentThread().sleep(1000);////to sleep the Thread for 1 Second (1000ms)
      }
      catch(Exception e){            
        System.out.printf("Error"+e);            
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

rua*_*akh 7

这是错误的,因为如果sleep发现线程被中断,它将抛出InterruptedException 并清除被中断的标志.然后吞下该异常,抑制该线程被中断的任何记录.相反,你应该写一些更像这样的东西:

public void run(){
    for(int i=1;i<=100;i++){

        System.out.println("THREAD VALUE AFTER 1 SECOND IS: "+i);

        if(i==3){
            Thread.currentThread().interrupt();
            gotoInform();
            break;
        }
        try{
            Thread.currentThread().sleep(1000);
        }
        catch(final Exception e){
            e.printStackTrace();
            if(e instanceof InterruptedException) {
                // just in case this Runnable is actually called directly,
                // rather than in a new thread, don't want to swallow the
                // flag:
                Thread.currentThread().interrupt();
            }
            return;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

(注意:我假设这不是"真正的"代码,而是你只是想了解线程中断是如何工作的.在"真正的"代码中,你几乎不需要中断当前线程办法.)