从Java中的synchronized上下文调用Thread.sleep() [英] calling Thread.sleep() from synchronized context in Java
问题描述
我已经读过 Thread.sleep()
将暂停当前运行的线程指定的时间,之后它将返回runnable状态,等待轮到它运行。
I have read that Thread.sleep()
will pause the currently running thread for the time specified after which it goes back to runnable state waiting for it's turn to run.
此外,如果从 synchronized
上下文调用, sleep()
不释放它所持有的锁。所以我想知道什么时候会释放锁。如果线程处于休眠状态,永远不会有机会运行,那么它将始终保持锁定,然后其他线程如何进入同步方法/块。
Also, if called from synchronized
context, sleep()
doesn't release the lock it holds. So I was wondering when it will release the lock. If the thread, put on sleep, never gets the chance to run so it will always keep the lock with itself and then how other threads get to enter synchronized methods/block.
我不确定我是否提出有效的问题。但请帮帮我。
I am not sure if I am asking valid question. But please help me out.
推荐答案
所以我想知道什么时候会释放锁。
So I was wondering when it will release the lock.
它将在退出 synchronized
块时释放锁定,而不是更早。
It will release the lock upon exit from the synchronized
block, and not earlier.
如果线程处于休眠状态,永远不会有机会运行,那么它将始终保持锁定自身,然后如何其他线程进入同步方法/块。
If the thread, put on sleep, never gets the chance to run so it will always keep the lock with itself and then how other threads get to enter synchronized methods/block.
很简单,其他线程将无法输入同步 on的代码睡眠线程的相同对象。
Quite simply, other threads will not be able to enter code that's synchronized on the same object that the sleeping thread.
总结一下,从 Thread.sleep()
调用一个 synchronized
块可能不太好。
To summarize, calling Thread.sleep()
from a synchronized
block is likely not a good idea.
这篇关于从Java中的synchronized上下文调用Thread.sleep()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!