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 ?
It doesn't have to. It just calls the operating system, which always sleeps the thread that called it.
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: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)
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.
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.