Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: why Thread.sleep() and yield() are static?

Why sleep() and yield() methods are defined as static methods in java.lang.Thread class?

like image 385
Rajan Garg Avatar asked Jun 26 '13 05:06

Rajan Garg


People also ask

Why yield method is static in Java?

A yield() method is a static method of Thread class and it can stop the currently executing thread and will give a chance to other waiting threads of the same priority. If in case there are no waiting threads or if all the waiting threads have low priority then the same thread will continue its execution.

What is the difference between sleep () and yield () methods of a thread?

Sleep() causes the currently executing thread to sleep (temporarily cease execution). Yield() causes the currently executing thread object to temporarily pause and allow other threads to execute.

Is thread sleep static wait?

On the other hand, Thread. sleep() is a static method that can be called from any context. Thread. sleep() pauses the current thread and does not release any locks.

What is wait () sleep () yield ()? What are differences among them?

The main difference between wait and sleep is that wait() method releases the acquired monitor when the thread is waiting while Thread. sleep() method keeps the lock or monitor even if the thread is waiting.


1 Answers

The code would only execute when someXThread was executing, in which case telling someYThread to yield would be pointless. So since the only thread worth calling yield on is the current thread, they make the method static so you won't waste time trying to call yield on some other thread.

like image 180
Suresh Atta Avatar answered Sep 22 '22 09:09

Suresh Atta