栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

清除Thread.interrupt()标志的方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

清除Thread.interrupt()标志的方法

问题的部分原因是,我不知道在那里清除中断标志的每个方法调用。

重要的是要阐明以下方法仅通过调用它们来清除中断标志:

Thread.interrupted()Thread.isInterrupted(true) -- added to your list

因此,

Thread.currentThread().isInterrupted()
应始终使用它代替。

下列方法将通过 立即 抛出中断标志来清除中断标志:

InterruptedException
如果它们被调用然后被中断, 或者 线程 已经
被中断然后被调用(请参阅下面的junit代码)。因此,不是清除标志而是抛出异常的方法。

您的初始列表:

Thread.interrupted()Thread.sleep(long)Thread.join()Thread.join(long)Object.wait()Object.wait(long)

添加到您的列表:

Thread.sleep(long, int)Thread.join(int, long)Thread.isInterrupted(true)Object.wait(int, long)BlockingQueue.put(...)BlockingQueue.offer(...)BlockingQueue.take(...)BlockingQueue.poll(...)Future.get(...)Process.waitFor()ExecutorService.invokeAll(...)ExecutorService.invokeAny(...)ExecutorService.awaitTermination(...)CompletionService.poll(...)CompletionService.take(...)CountDownLatch.await(...)CyclicBarrier.await(...)Semaphore.acquire(...)Semaphore.tryAcquire(...)Lock.lockInteruptibly()Lock.tryLock(...)

请注意 ,捕获到的 任何
代码的正确模式

InterruptedException
是立即重新中断线程。如果其他人依赖该
thread.isInterrupted()
方法,我们会这样做:

try {    ...} catch (InterruptedException e) {    // immediately re-interrupt the thread    Thread.currentThread().interrupt();    // log the exception or [likely] quit the thread}

JUnit代码演示了其中的一些功能:

assertFalse(Thread.currentThread().isInterrupted());// you can do this from another thread by saying: someThread.interrupt();Thread.currentThread().interrupt();// this method does _not_ clear the interrupt flagassertTrue(Thread.currentThread().isInterrupted());// but this one _does_ and should probably not be usedassertTrue(Thread.interrupted());assertFalse(Thread.currentThread().isInterrupted());Thread.currentThread().interrupt();assertTrue(Thread.currentThread().isInterrupted());try {    // this throws immediately because the thread is _already_ interrupted    Thread.sleep(1);    fail("will never get here");} catch (InterruptedException e) {    // and when the InterruptedException is throw, it clears the interrupt    assertFalse(Thread.currentThread().isInterrupted());    // we should re-interrupt the thread so other pre can use interrupt status    Thread.currentThread().interrupt();}assertTrue(Thread.currentThread().isInterrupted());


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/486659.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号