线程中断:它会取消即将到来的wait()调用吗? [英] Thread interrupt: will it cancel oncoming wait() call?

查看:575
本文介绍了线程中断:它会取消即将到来的wait()调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程有一个传入的作业队列( LinkedList 包含作业描述)。当没有工作要处理时,线程阻塞队列上的 wait()

I have a thread which has an incoming job queue (a LinkedList containing job descriptions). The thread blocks with wait() on the queue when there's no job to work on. An external job dispatcher object awakes it with notify() when it places new jobs on the queue.

在关闭时,外部作业分派器对象会使用 notify()的我的程序我调用 interrupt()在线程。当线程等待 wait()中的作业时,这会引发 InterruptedException 。我的问题是:如果我中断线程而不阻塞,但做某种工作,处理的项目是队列中的最后一个(因此队列现在是空的),并执行粘贴 isInterrupted ()在中断标志设置之前检查它是否再次调用 wait()它会抛出一个 InterruptedException ,因为中断标志已经设置或线程永远等待,因为新的作业永远不会到达队列,没有人来中断等待? / p>

At shutdown of my program i call interrupt() on the Thread. This raises InterruptedException when the Thread awaits for jobs in wait(). My question is: what will happen if i interrupt the Thread while it's not blocking but doing some kind of work, the processed item was the last in the queue (so queue is now empty) and execution pasts the isInterrupted() check before the interrupted flag is set so it calls wait() again? Will it throw an InterruptedException because the interrupted flag has already been set or the thread waits forever because new jobs will never arrive to the queue and there's no one to interrupt the wait?

推荐答案

是的,被中断的线程将在调用wait()时抛出一个InterruptedException。这是很简单的测试自己。

yes, your interrupted thread will throw an InterruptedException upon calling wait(). this is pretty simple to test for yourself.

public class TestInt {
    public static void main(String[] args) throws Exception
    {
        Thread.currentThread().interrupt();

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

Object.wait()


InterruptedException - 之前
当前线程正在等待通知。抛出此异常时,当前
线程的中断状态将被清除。

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.

这篇关于线程中断:它会取消即将到来的wait()调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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