interrupt,interrupted,isInterrupted的区别

1,064 阅读2分钟

1.interrupted

/**
测试是否当前线程已经中断。 该线程的中断状态由该方法清除。 换句话说,如果该方法是连续被调用两次,第二次调用将返回false(除非当前线程被再次中断,之后在第一次调用已清除了其中断状态)。
忽略,因为一个线程是不是在中断的时间活着的线程中断将通过此方法返回false来体现。
返回:
true如果当前线程已经中断; false否则没被中断
**/
public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }

2.isInterrupted

/**
测试线程是否已经中断。 线程的中断状态不受该方法的影响。
忽略,因为一个线程是不是在中断的时间活着的线程中断将通过此方法返回false来体现。

返回:
true如果该线程已经中断; false否则。
*/
 public boolean isInterrupted() {
        return isInterrupted(false);
    }
  1. interrupt
 /**
 interrupt() 方法只是改变中断状态而已,它不会中断一个正在运行的线程。
 这一方法实际完成的是,给受阻塞的线程发出一个中断信号,这样受阻线程就得以退出阻塞的状态。
 更确切的说,如果线程被Object.wait, Thread.join和Thread.sleep三种方法之一阻塞,此时调用该线程的interrupt()方法,那么该线程将抛出一个 InterruptedException中断异常(该线程必须事先预备好处理此异常),从而提早地终结被阻塞状态。如果线程没有被阻塞,这时调用 interrupt()将不起作用,直到执行到wait(),sleep(),join()时,才马上会抛出 InterruptedException。
 */
 public void interrupt() {
         if (this != Thread.currentThread())
             checkAccess();
 
         synchronized (blockerLock) {
             Interruptible b = blocker;
             if (b != null) {
                 interrupt0();           // Just to set the interrupt flag
                 b.interrupt(this);
                 return;
             }
         }
         interrupt0();
     }
  1. 测试 interrupted,isInterrupted
 public static void main(String[] args) {
         new Thread(new Demo()).start();
 
     }
 
 
     static class Demo implements Runnable{
 
         @Override
         public void run() {
             Thread myThread=Thread.currentThread();
 
             System.out.println("没打断之前 ,返回结果:"+ myThread.isInterrupted());
 
             myThread.interrupt();
 
             System.out.println("打断线程 ,返回结果:"+ myThread.isInterrupted());
 
             Thread.interrupted();
 
             System.out.println("执行 interrupted ,返回结果:"+ myThread.isInterrupted());
         }
     }

测试结果

没打断之前 ,返回结果:false
打断线程 ,返回结果:true
执行 interrupted ,返回结果:false

可以看出isInterrupted仅仅是判断了线程是否中断的状态,interrupted执行完之后,清楚了当前线程的中断状态

5.测试interrupt

public class InterruputThread implements Runnable{

    @Override
    public void run() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            System.out.println("线程被中断");
            e.printStackTrace();
        }
    }
}



    public static void main(String[] args) {
        InterruputThread thread=new InterruputThread();
        Thread interruptedThread= new Thread(thread);
        interruptedThread.start();
        interruptedThread.interrupt();
    }

测试结果

java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.example.list.InterruputThread.run(InterruputThread.java:13)
	at java.lang.Thread.run(Thread.java:748)
线程被中断

可以看出线程在阻塞在sleep状态,被打断后,抛出了InterruptedException异常