Thread的interrupt、isInterrupted、interrupted源码探索

来源:互联网 发布:js uint8array int 编辑:程序博客网 时间:2024/05/29 14:31
java.lang.Thread
public void interrupt()
Interrupts this thread.
Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.//自己中断自己永远是可以的
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.//调用上述wait、join、sleep方法抛出InterruptedException异常后,中断状态会被清除,也就是中断状态是false
If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a java.nio.channels.ClosedByInterruptException.
If this thread is blocked in a java.nio.channels.Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.
If none of the previous conditions hold then this thread's interrupt status will be set.
Interrupting a thread that is not alive need not have any effect.//中断没有alive的线程没有任何效果
Throws:

SecurityException - if the current thread cannot modify this thread




java.lang.Thread
public boolean isInterrupted()
Tests whether this thread has been interrupted. The interrupted status of the thread is unaffected by this method.//测试这条线程是否被中断,中断状态不会变。但是interrupted会使中断状态由true转为false
A thread interruption ignored because a thread was not alive at the time of the interrupt will be reflected by this method returning false.
Returns:
true if this thread has been interrupted; false otherwise.
See Also:
interrupted()




java.lang.Thread
public static boolean interrupted()//interrupted结尾加ed表示过去式,让中断状态成为过去,假如当前线程已经是中断(true),让中断状态由true变为false
Tests whether the current thread has been interrupted. The interrupted status of the thread is cleared by this method. In other words, if this method were to be called twice in succession, the second call would return false (unless the current thread were interrupted again, after the first call had cleared its interrupted status and before the second call had examined it).//如果这个方法两次成功调用,那么第二次会返回false,因为第一次已经将中断状态由true变为false了。(除非在第一次调用和第二次调用之间,当前线程再一次执行Thread.currentThread.interrupt()方法)
A thread interruption ignored because a thread was not alive at the time of the interrupt will be reflected by this method returning false.
Returns:
true if the current thread has been interrupted; false otherwise.
See Also:
isInterrupted()

0 0