thread中断相关方法区别interrupt、interrupted和isInterrupted

interrupt

中断此线程。调用该方法的线程的状态为将被置为"中断"状态,线程并不会停止运行。
如果在调用Object类的wait() , wait(long)或wait(long, int)方法或join() , join(long) , join(long, int)方法时阻塞了该线程, sleep(long)或sleep(long, int)此类的方法,则其中断状态将被清除,并将收到InterruptedException 。(JUC锁或队列相关类抛出InterruptedException 异常前,会调用下面静态方法interrupted,清除中断状态。所以这就是为什么catch到此异常时需要再次抛出或再次调用中断,否则就会丢掉该线程的中断状态。例如:主线程监听子线程中断状态做出不同处理,如果子线程抛出此异常没有正确处理,则主线程就感知不到子线程中断状态
如果此线程在InterruptibleChannel的I / O操作中被阻止,则该通道将被关闭,该线程的中断状态将被设置,并且该线程将收到java.nio.channels.ClosedByInterruptException 。
如果此线程在java.nio.channels.Selector被阻塞,则将设置该线程的中断状态,并且它将立即从选择操作中返回(可能具有非零值),就像调用选择器的wakeup方法一样。
如果上述条件均不成立,则将设置该线程的中断状态。
中断未运行的线程不会产生任何效果 

interrupted

静态方法。测试当前线程是否已被中断。 通过此方法可以清除线程的中断状态。 换句话说,如果要连续两次调用此方法,则第二次调用将返回false(除非当前线程在第一次调用清除其中断状态之后且在第二次调用检查其状态之前再次中断)。
由于此方法返回false,因此会反映出线程中断而被忽略,因为该线程在中断时还没有处于活动状态

  public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }

isInterrupted

测试此线程是否已被中断。 线程的中断状态不受此方法的影响。
由于此方法返回false,因此会反映出线程中断而被忽略,因为该线程在中断时还没有处于活动状态

   public boolean isInterrupted() {
        return isInterrupted(false);
    }

isInterrupted(boolean)

    private native boolean isInterrupted(boolean ClearInterrupted);

 可以看出 interrupted 和 isInterrupted都是调用了内部的本地方法isInterrupted方法,参数即为是否清楚中断状态。

interrupted 、isInterrupted区别:interrupted 作用于当前线程,isInterrupted 作用于调用该方法的线程对象。例如:在主线程main中调用子线程sub的isInterrupted方法,同时调用静态的interrupted方法。则isInterrupted作用于子线程sub,interrupted作用于主线程main

猜你喜欢

转载自blog.csdn.net/sinat_33472737/article/details/114681170