java - 线程中断 : will it cancel oncoming wait() call?

标签 java multithreading concurrency wait

我有一个线程,它有一个传入的作业队列(一个包含作业描述的 LinkedList)。当没有工作可处理时,线程会在队列中用 wait() 阻塞。外部作业调度程序对象在将新作业放入队列时使用 notify() 将其唤醒。

在我的程序关闭时,我在线程上调用了 interrupt()。当线程等待 wait() 中的作业时,这会引发 InterruptedException。我的问题是:如果我在 Thread 没有阻塞但在做某种工作时中断它会发生什么,处理的项目是队列中的最后一个(因此队列现在是空的)并且执行通过 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();
        }    
    }    
}

另外,请注意 Object.wait() 的 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.

关于java - 线程中断 : will it cancel oncoming wait() call?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6698977/

相关文章:

java - 出于线程调度目的,线程被禁用。这意味着什么?

java - Spring Boot - 使用 Gmail 发送电子邮件

java - 将 JMenuItem 添加到 JMenu 会导致菜单栏消失

java - Selenium HtmlUnitDriver 登录网站

Python - 让父线程处理子线程异常

python - Python2.7中带超时的锁

java - 对静态方法或返回 lambda 的静态方法的方法引用

java - 如何在线程内更新 JApplet GUI?

发出并发请求时,php curl localhost 很慢

c++ - 为什么锁定 std::mutex 不会阻塞线程