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 ?
Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t. sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.
Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.
Sleep method causes the current thread to immediately block for the number of milliseconds or the time interval you pass to the method, and yields the remainder of its time slice to another thread. Once that interval elapses, the sleeping thread resumes execution. One thread cannot call Thread. Sleep on another thread.
Multithreading is the ability of a program or an operating system to enable more than one user at a time without requiring multiple copies of the program running on the computer. Multithreading can also handle multiple requests from the same user.
how does it figure out the current thread of execution?
It doesn't have to. It just calls the operating system, which always sleeps the thread that called it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With