在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 02:00:13  来源:igfitidea点击:

calling Thread.sleep() from synchronized context in Java

javamultithreadingsynchronizedthread-sleep

提问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 synchronizedcontext, 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 synchronizedblock, 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 synchronizedblock is likely not a good idea.

总而言之,Thread.sleep()synchronized块调用可能不是一个好主意。

回答by nosid

If you use Object.waitinstead of Thread.sleep, the lock from the synchronized block will be released.

如果使用Object.wait而不是Thread.sleep,来自同步块的锁将被释放。