从多个线程调用时 Thread.sleep() 如何工作
sleep() 是 Thread 类的静态方法。从多个线程调用时它是如何工作的。以及它如何确定当前的执行线程。 ?
或者可能是一个更通用的问题是如何从不同线程调用静态方法?不会有并发问题吗?
sleep() is a static method of class Thread. How does it work when called from multiple threads. and how does it figure out the current thread of execution. ?
or may be a more generic Question would be How are static methods called from different threads ? Won't there be any concurrency problems ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
没必要。它只是调用操作系统,而操作系统总是使调用它的线程处于休眠状态。
It doesn't have to. It just calls the operating system, which always sleeps the thread that called it.
sleep
方法会休眠当前线程,因此如果您从多个线程调用它,它将休眠每个线程。还有 currentThread 静态方法,允许您获取当前正在执行的线程。The
sleep
method sleeps the current thread so if you are calling it from multiple threads it will sleep each of those threads. Also there's the currentThread static method which allows you to get the current executing thread.如果一个或多个线程修改共享状态,而另一个线程使用相同的状态,则仅存在潜在的并发问题。 sleep() 方法没有共享状态。
There is only a potential concurrency problem if one or more thread modifies shared state while another thread uses the same state. There is no shared state for the sleep() method.
Thread.sleep(long)
在java.lang.Thread
类中本机实现。以下是其 API 文档的一部分:sleep 方法使调用它的线程休眠。(基于 EJP 的注释)
确定当前正在执行的线程(调用它并使其休眠)。Java 方法可以通过调用 Thread.currentThread() 来确定哪个线程正在执行它。可以从任意数量的线程同时调用方法(静态或非静态)。只要您的方法线程安全,就不会有任何并发问题。
仅当多个线程在没有正确同步的情况下修改类或实例的内部状态时,您才会遇到问题。
Thread.sleep(long)
is implemented natively in thejava.lang.Thread
class. Here's a part of its API doc:The sleep method sleeps the thread that called it.(Based on EJP's comments)
determines the currently executing thread (which called it and cause it to sleep).Java methods can determine which thread is executing it by callingThread.currentThread()
Methods (static or non static) can be called from any number of threads simultaneously. Threre will not be any concurrency problems as long as your methods are thread safe.
You will have problems only when multiple Threads are modifying internal state of class or instance without proper synchronization.
当虚拟机遇到
sleep(long)
语句时,它会中断当前运行的线程。那一刻的“当前线程”始终是调用 Thread.sleep() 的线程。然后它说:改变线程称为“屈服”。 (注意:你可以通过调用
Thread.yield();
自行yield)因此,它不必弄清楚当前的Thread是什么。调用 sleep() 的始终是线程。
注意:您可以通过调用
Thread.currentThread();
获取当前线程。一个简短的示例:
MyRunnable
的run()
方法:When the virtual machine encounters a
sleep(long)
-statement, it will interrupt the Thread currently running. "The current Thread" on that moment is always the thread that calledThread.sleep()
. Then it says:Changing thread is called "to yield". (Note: you can yield by yourself by calling
Thread.yield();
)So, it doesn't have to figure out what the current Thread is. It is always the Thread that called sleep().
Note: You can get the current thread by calling
Thread.currentThread();
A short example:
MyRunnable
itsrun()
method: