在 Java 中从同步上下文调用 Thread.sleep()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10663920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
calling Thread.sleep() from synchronized context in Java
提问by Anand
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.
我读过它Thread.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.
此外,如果从synchronized
上下文调用,sleep()
则不会释放它持有的锁。所以我想知道它什么时候会释放锁。如果线程处于睡眠状态,则永远不会有机会运行,因此它将始终保持自身锁定,然后其他线程如何进入同步方法/块。
I am not sure if I am asking valid question. But please help me out.
我不确定我是否在问有效的问题。但请帮帮我。
回答by NPE
So I was wondering when it will release the lock.
所以我想知道它什么时候会释放锁。
It will release the lock upon exit from the synchronized
block, and not earlier.
它将在退出synchronized
块时释放锁,而不是更早。
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.
如果线程处于睡眠状态,则永远不会有机会运行,因此它将始终保持自身锁定,然后其他线程如何进入同步方法/块。
Quite simply, other threads will not be able to enter code that's synchronized on the same objectthat the sleeping thread.
很简单,其他线程将无法输入在与休眠线程相同的对象上同步的代码。
To summarize, calling Thread.sleep()
from a synchronized
block is likely not a good idea.
总而言之,Thread.sleep()
从synchronized
块调用可能不是一个好主意。
回答by nosid
If you use Object.wait
instead of Thread.sleep
, the lock from the synchronized block will be released.
如果使用Object.wait
而不是Thread.sleep
,来自同步块的锁将被释放。