线程由于等待 JVM 处理的对象锁而处于阻塞状态是如何造成的
我已经看到线程可以通过不同的方式进入阻塞状态。我有兴趣知道线程处于阻塞状态后到底会发生什么。如何恢复到运行状态?
如果它被 sleep(time) 阻塞,那么它会在 time 毫秒后移动到可运行队列。如果它在 I/O 操作上被阻塞,一旦完成,它就会进入可运行队列。
当它等待对象锁时,它如何进入可运行队列?它如何知道它等待的对象上的锁现在可用?有人还可以解释 I/O 上阻塞线程如何工作的内部原理吗?
如果我对上述任何主题的理解不正确,请纠正我。
I have seen there are different ways a thread could get to blocked state. I'm interested to know what exactly happens after a thread is in blocked state. How does it get back to running state?
If its blocked by sleep(time) then it moves to the runnable queue after time milli secs. If its blocked on a I/O operation it gets into the runnable queue once that is done.
How does it get to the runnable queue when it is waiting on an objects lock? How does it know that the lock on the object its waiting for is now available? Can some one also explain the internals of how the blocked thread on I/O works?
Please correct me if my understanding on any of the above topics isn't right..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果线程由于尝试进入
synchronized
块而被阻塞,则该线程会被自动标记当另一个线程(持有锁)通过退出同一对象的同步块来释放锁时,该线程可运行。如果当前线程由于调用
someObject.wait()
而被阻塞,则当另一个线程调用someObject.notify()
时,该线程将被“释放”。在字节码级别上,它看起来如下:
如果其他线程已经持有
obj
的锁,则该线程将挂在monitorenter
上,直到另一个线程调用monitorexit
代码>.JLS 没有指定如何实现
monitorenter
和monitorexit
的具体细节。也就是说,它依赖于 JVM/OS。有关更多详细信息,请参阅 JLS 等待集和通知 。
If the thread is blocked due to trying to enter a
synchronized
block, the thread is automatically marked as runnable when the other thread (holding the lock) releases the lock by exiting from asynchronized
block of the same object.If the current thread is blocked due to a call to
someObject.wait()
, the thread is "released" when another thread callssomeObject.notify()
.On the bytecode level it looks as follows:
If someone else already holds the lock of
obj
, the thread will hang onmonitorenter
until the other thread callsmonitorexit
.The exact details of how
monitorenter
andmonitorexit
should be implement is not specified by the JLS. That is, it is JVM/OS dependent.For further details, refer to JLS Wait Sets and Notifications.
在接近代码的级别上,它看起来像这样:
线程 1:
线程 2:
一般来说,您应该记住 Thread.sleep() 持有资源上的锁,但 Thread.wait() 释放锁并且可以被其他线程通知。
On a close-to-code level it looks like this:
Thread 1:
Thread 2:
In general you should keep in mind that Thread.sleep() holds the lock on the resources, but Thread.wait() releases the locks and can be notified by other Threads.
AFAIK JVM 使用本机线程。因此,管理线程调度和上下文切换的是操作系统而不是 JVM。
您可以查看实际的 JVM 源代码。它是开放的。
AFAIK JVM use native threads. So it is OS not JVM that manage thread schedule and context switching.
You can look at actual JVM source code. It's open.