java – 线程中断:它会取消接收wait()调用吗?

前端之家收集整理的这篇文章主要介绍了java – 线程中断:它会取消接收wait()调用吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个线程,它有一个传入的作业队列(一个包含作业描述的LinkedList).当没有任务可以工作时,线程在队列中等待().当外部作业调度器对象在队列中放置新作业时,会用notify()唤醒它.

在我的程序关闭时,我在Thread上调用interrupt().当线程等待wait()中的作业时,这会引发InterruptedException.我的问题是:如果我中断线程,而不是阻塞但做某种工作,那么会发生什么,处理的项目是队列中的最后一个(所以队列现在是空的),并且在中断之前执行isInterrupted()检查标志设置好,它再​​次调用wait()?它会抛出一个InterruptedException,因为中断的标志已经设置或线程永远等待,因为新的作业永远不会到达队列,没有人打断等待?

解决方法

是的,你中断的线程会在调用wait()时抛出一个InterruptedException异常.这是很简单的测试自己.
public class TestInt {
    public static void main(String[] args) throws Exception
    {
        Thread.currentThread().interrupt();

        synchronized(TestInt.class) {
            TestInt.class.wait();
        }    
    }    
}

还要注意Objectodwait()的javaodc:

InterruptedException – if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.

原文链接:https://www.f2er.com/java/120907.html

猜你在找的Java相关文章