Thread.interrupt()和Thread.interrupted()到底如何工作? [英] How exactly does Thread.interrupt() and Thread.interrupted() work?

查看:139
本文介绍了Thread.interrupt()和Thread.interrupted()到底如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从设置线程状态的角度来看,我对这两种方法不清楚.

I am not clear regarding these two methods from the perspective of setting the status of the thread.

Java文档说Thread.interrupt()设置线程中断状态标志,并调用Thread.interrupted()方法给出线程的状态并清除该标志.

Java Docs say that Thread.interrupt() sets the threads interrupt status flag and calling the Thread.interrupted() method gives the status of the thread and clears the flag.

在实际场景中使用它时..

When this comes to use in real scenarios..??

推荐答案

当其他某个线程调用Thread.interrupt()时,该方法会将Thread的中断状态标志(最初为false)设置为true.如果Thread处于Thread.sleep(),Thread.join()或Object.wait()之类的阻塞方法中,则它将解除阻塞并抛出InterruptedException.

When some other thread calls Thread.interrupt() the method sets Thread's interrupt status flag (initially false) to true. If the Thread is in blocking method like Thread.sleep(), Thread.join() or Object.wait() it unblocks and throws an InterruptedException.

Thread.interrupted()是一个静态方法,可用于检查中断状态标志的当前值,是或否.它还清除中断状态,将标志设置为false.也就是说,连续两次调用它可能即使第二次返回true也会第二次返回false(除非线程再次被中断,在第一次调用之后将中断状态标志设置为true)

Thread.interrupted() is a static method which can be use to check the current value of interrupt status flag, true or false. It also clears the interrupt status , setting the flag to false. That is calling it twice in a row may likely return false the second time even if it returned true the first time (unless the thread were interrupted again, setting the interrupt status flag to true after the first call)

请注意第三个方法Thread.isInterrupted(),它可以在不重置的情况下检查中断状态.

Note a third method Thread.isInterrupted() which can check the interrupt status without resetting.

典型用例:

  1. 异常阻止操作
  2. 确定是否需要在某个逻辑保存/停止点继续执行长指令序列
  3. 确定是否需要在开始长期运行的任务之前继续执行一系列指令
  4. 停止执行迭代过程,否则该过程将一直持续下去(while(true)不好,while(!Thread.interrupted())更好)
  1. Break exceptionally from a blocking operation
  2. Determine if it is desired to continue a long sequence of instructions at some logical save/stop point
  3. Determine if it is desired to continue a sequence of instructions prior to beginning a long running task
  4. Stop executing an iterative process that would otherwise continue into perpetuity (while(true) is bad, while(!Thread.interrupted()) is better)

这篇关于Thread.interrupt()和Thread.interrupted()到底如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆