interrupt()、interrupted()、isInterrupted()
这三个方法都涉及到多线程的一个知识点----中断机制
三个中断方法
中断标识位是JDK源码看不到的,是虚拟机线程实现层面的。
下面结合代码逐一看一下这三个方法的作用,以及为什么中断标识位是虚拟机实现层面的:
1、interrupt()
1 public void interrupt() { 2 if (this != Thread.currentThread()) 3 checkAccess(); 4 5 synchronized (blockerLock) { 6 Interruptible b = blocker; 7 if (b != null) { 8 interrupt0(); // Just to set the interrupt flag 9 b.interrupt(); 10 return; 11 } 12 } 13 interrupt0(); 14 }
结果
1 /* Some private helper methods */ 2 private native void setPriority0(int newPriority); 3 private native void stop0(Object o); 4 private native void suspend0(); 5 private native void resume0(); 6 private native void interrupt0();
分两部分看:
(1)第一部分的第8行注释说得很清楚了,interrupt0()方法的作用是"Just to set the interrupt flag",即方法的作用仅仅是设置中断标识位
(2)第二部分的第6行就是interrupt0()方法的原型,由于方法是被native修饰的,很明显这是一个本地方法,是Java虚拟机实现的
2、isInterrupted()
方法唯一的作用只是测试线程是否已经中断,中断标识位的状态并不受到该方法的影响,看一下Java是如何实现这个方法的:
1 /** 2 * Tests whether this thread has been interrupted. The <i>interrupted 3 * status</i> of the thread is unaffected by this method. 4 * 5 * <p>A thread interruption ignored because a thread was not alive 6 * at the time of the interrupt will be reflected by this method 7 * returning false. 8 * 9 * @return <code>true</code> if this thread has been interrupted; 10 * <code>false</code> otherwise. 11 * @see #interrupted() 12 * @revised 6.0 13 */ 14 public boolean isInterrupted() { 15 return isInterrupted(false); 16 }
1 private native boolean isInterrupted(boolean ClearInterrupted);
注意一下第一部分的第2行和第3行,"The interrupted statis of the thread is unaffected by this method",即线程的中断状态不受到这个方法的影响。
最终调用的是isInterrupted(boolean ClearInterrupted),这个方法是一个native的,看得出也是Java虚拟机实现的。
方法的参数ClearInterrupted,顾名思义,清除中断标识位,这里传递false,明显就是不清除
3、interrupted()
方法的作用是测试当前线程是否已经中断,线程的中断标识位由该方法清除。
换句话说,连续两次调用该方法的返回值必定是false。
看一下这个方法是如何实现的:
1 /** 2 * Tests whether the current thread has been interrupted. The 3 * <i>interrupted status</i> of the thread is cleared by this method. In 4 * other words, if this method were to be called twice in succession, the 5 * second call would return false (unless the current thread were 6 * interrupted again, after the first call had cleared its interrupted 7 * status and before the second call had examined it). 8 * 9 * <p>A thread interruption ignored because a thread was not alive 10 * at the time of the interrupt will be reflected by this method 11 * returning false. 12 * 13 * @return <code>true</code> if the current thread has been interrupted; 14 * <code>false</code> otherwise. 15 * @see #isInterrupted() 16 * @revised 6.0 17 */ 18 public static boolean interrupted() { 19 return currentThread().isInterrupted(true);
1 private native boolean isInterrupted(boolean ClearInterrupted);
同样,第2行和第3行的注释已经写得很清楚了,"Theinterruptedstatusofthethreadisclearedbythismethod",即线程的中断状态由此方法清除。
另外,interrupted()方法和isInterrupted()方法调用的是同一个native方法,无非这个方法传入的是true,表示清除中断标识位
参考:
https://www.jb51.net/article/128207.htm