Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Thread.sleep() work when called from multiple threads

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 ?

like image 560
JWhiz Avatar asked Aug 21 '10 06:08

JWhiz


People also ask

Can sleep () method causes another thread to sleep?

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.

What happens when a sleep is called on 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.

Does thread sleep block other threads?

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.

When multiple threads execute simultaneously it is called?

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.


2 Answers

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.

like image 171
user207421 Avatar answered Sep 23 '22 04:09

user207421


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.

like image 38
Darin Dimitrov Avatar answered Sep 23 '22 04:09

Darin Dimitrov