java - 当线程在 wait() 上阻塞时被中断会发生什么?

标签 java multithreading concurrency interrupted-exception

考虑到 wait() 只能在同步上下文中调用,随后释放监视器,直到另一个线程在同一对象上调用 notify/nofityAll,

假设线程 A 在 wait() 上阻塞,导致线程 B 获取锁。现在如果我们中断线程 A,控制权会立即转移到线程 A 吗?在这种情况下,由于处理 InterrupException 的 try catch block 在同步上下文中,并且由于一次只有一个线程可以持有监视器,线程 B 会发生什么?在线程 A 完成执行之前它是否应该进入阻塞状态?

提前致谢

最佳答案

阅读文档确实有帮助:

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#wait%28long%29

因此,当线程被中断时,必须重新获取Object的monitor来恢复异常抛出前的同步状态。这同样适用于在经过指定的时间量后从 wait(long) 调用返回。

The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It then competes in the usual manner with other threads for the right to synchronize on the object; once it has gained control of the object, all its synchronization claims on the object are restored to the status quo ante - that is, to the situation as of the time that the wait method was invoked. Thread T then returns from the invocation of the wait method. Thus, on return from the wait method, the synchronization state of the object and of thread T is exactly as it was when the wait method was invoked.

If the current thread is interrupted by another thread while it is waiting, then an InterruptedException is thrown. This exception is not thrown until the lock status of this object has been restored as described above.

关于java - 当线程在 wait() 上阻塞时被中断会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8071097/

相关文章:

java - Java 中的线程。在新线程中创建每个图形,循环不起作用

python - Qt (PyQt) 事件循环内的 xmlrpc?

scala - 为什么 Scala Futures 一次只运行 2 个?

objective-c - 如何在只处理最新请求的 iOS 中实现工作队列?

java - Spring Security 中的记住我服务

java - 如何使用 Gradle 测试编译后的 JAR 文件

c# - 在 C# 中,使用 for 循环迭代数组是线程安全操作吗?使用 foreach 循环迭代 IEnumerable<T> 怎么样?

java - 在 MVC 模式中,模型可以交互/修改 View 吗?

java - 向上转型时,Java 如何处理字段?

java - 不安全发布并发java