java线程的中断

判断线程是否被中断的两个方法:interrupted()方法与 isInterrupted()方法都是反映当前线程的是否处于中断状态的。
interrupted()方法,这是一个静态方法源码如下:
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
它测试的是当前线程(current thread)的中断状态,且这个方法会清除中断状态。当前线程指的是当前执行的线程,也就是当前执行interrupted()的线程。

静态方法currentThread()
---------------------------
这个方法返回执行它的线程。
参考:http://www.java2s.com/Tutorials/Java/Java_Thread/0040__Java_Thread_Current.htm
The Thread class static method currentThread() returns the reference of the Thread object that calls this method.Consider the following statement:
Thread  t = Thread.currentThread();
The statement will assign the reference of the thread object that executes the above statement to the variable t.
 
 isInterrupted()方法
 ---------------------------
 实例方法(它测试的是实例对象所表示的线程的中断状态)。线程的状态不会清除。
 
 中断
 --------------------------
 Java选择用一种协作式的中断机制实现中断。协作式中断的原理很简单,其核心是先对中断标识进行标记,某线程设置某线程的中断标识位,被标记了中断位的线程在适当的时间节点会抛出异常,捕获异常后做相应的处理。
 
 void java.lang.Thread.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. 

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.

线程发生了中断了,如果线程中有上面提到的会阻塞的方法,那么线程将会被中断抛出中断异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值