interrupted()

  这个问题首先由如何终止一个线程引起的,如果想要终止一下线程,该怎么做呢:

  1、Thread.stop()

  2、标识变量

  3、Thread.interrupt()

  Thread.stop()是一个选择

  问题一:这个方法已经被废止了,为什么呢?

  引用Java doc的解释:

  Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as the ThreadDeath exception propagates up the stack.) If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. Such objects are said to be damaged. When threads operate on damaged objects, arbitrary behavior can result. This behavior may be subtle and difficult to detect, or it may be pronounced. Unlike other unchecked exceptions, ThreadDeath kills threads silently; thus, the user has no warning that his program may be corrupted. The corruption can manifest itself at any time after the actual damage occurs, even hours or days in the future.

  大致意思就是stop会使所有的解锁所有monitor,因此任何被该monitor保护的对象进入一种inconsistent(不一致)的状态,进入这种状态的对象可以说是已经损毁了,如果线程操作这些损坏的对象的时候则有引起ThreadDeath Exception,这个Exception会悄无声息的kill掉线程。

  问题二:ThreadDeath难道不能捕获么?

  理论上是可以的。

  但是实际操作中,ThreadDeath有可能发生在任何时间,任何位置, so…

  剩下的两种方式都是ok的,应用场景略有不同:

  标识变量:

  一般用在可以频繁检查变量的状态的情况。

  该标识变量需要被volitile修饰或者是访问的时候用syncronized 锁住。

  类似:

  while(!stop) {}

  interrupt():

  注意这个方法并没有立即将thread终止,而是仅仅标识一个interrupt的状态,如果对应线程进入某些特定的状态,这些状态会清除该状态,并接到InterruptException.

  这些状态包括:

  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 ClosedByInterruptException.

  If this thread is blocked in a 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.

  注意与另外两个方法的区别:

  isInterrupted() : 判断当前的是否有interrupt的状态,并不会清除状态

  interrupted(): 静态方法,会清除interrupt状态,并根据返回值判断是否清除了状态。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值