As currently executing thread while it encounters the call sleep() then thread moves immediately into sleeping stat.
Whereas for yield() thread moves into runnable state / ready state.
We can prevent a thread from execution by using any of the 3 methods of Thread class:
yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority or higher priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent.
join() If any executing thread t1 calls join() on t2 (i.e. t2.join()) immediately t1 will enter into waiting state until t2 completes its execution.
sleep() Based on our requirement we can make a thread to be in sleeping state for a specified period of time (hope not much explanation required for our favorite method).
sleep() causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).
yield() basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should. Otherwise, the current thread will continue to run.
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.
Read [this] (Link Removed) for a good explanation of the topic.
Sleep causes thread to suspend itself for x milliseconds while yield suspends the thread and immediately moves it to the ready queue (the queue which the CPU uses to run threads).
Yield : will make thread to wait for the currently executing thread and the thread which has called yield() will attaches itself at the end of the thread execution. The thread which call yield() will be in Blocked state till its turn.
Sleep : will cause the thread to sleep in sleep mode for span of time mentioned in arguments.
Join : t1 and t2 are two threads , t2.join() is called then t1 enters into wait state until t2 completes execution. Then t1 will into runnable state then our specialist JVM thread scheduler will pick t1 based on criteria's.
Yield(): method will stop the currently executing thread and give a chance to another thread of same priority which are waiting in queue. If thier is no thread then current thread will continue to execute. CPU will never be in ideal state.
Sleep(): method will stop the thread for particular time (time will be given in milisecond). If this is single thread which is running then CPU will be in ideal state at that period of time.
Both are static menthod.
Yield: It is a hint (not guaranteed) to the scheduler that you have done enough and that some other thread of same priority might run and use the CPU.
Thread.sleep();
Sleep: It blocks the execution of that particular thread for a given time.
TimeUnit.MILLISECONDS.sleep(1000);
yield(): yield method is used to pause the execution of currently running process so that other waiting thread with the same priority will get CPU to execute.Threads with lower priority will not be executed on yield. if there is no waiting thread then this thread will start its execution.
join(): join method stops currently executing thread and wait for another to complete on which in calls the join method after that it will resume its own execution.
For detailed explanation, see this link.
One way to request the current thread to relinquish CPU so that other threads can get a chance to execute is to use yield in Java.
yield is a static method.
It doesn't say which other thread will get the CPU.
It is possible for the same thread to get back the CPU and start its execution again.
public class Solution9 {
public static void main(String[] args) {
yclass yy = new yclass ();
Thread t1= new Thread(yy);
t1.start();
for (int i = 0; i <3; i++) {
Thread.yield();
System.out.println("during yield control => " + Thread.currentThread().getName());
}
}
}
class yclass implements Runnable{
#Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("control => " + Thread.currentThread().getName());
}
}
}
sleep()causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).
yield()basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should. Otherwise, the current thread will continue to run.
sleep() causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).
yield() basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should. Otherwise, the current thread will continue to run.
Both methods are used to prevent thread execution.
But specifically,
sleep():
purpose:if a thread don't want to perform any operation for particular amount of time then we should go for sleep().for e.x. slide show .
yield():
purpose:if a thread wants to pause it's execution to give chance of execution to another waiting threads of same priority.thread which requires more execution time should call yield() in between execution.
Note:some platform may not provide proper support for yield() . because underlying system may not provide support for preemptive scheduling.moreover yield() is native method.
Related
I was reading about yield. It is being told that if a thread is running long and if another thread who is going to run for short time need to wait for long running thread to finish its processing. But my question is as per thread scheduler, no thread will run till its completion in one go. it has to oscillate between running and ready states. so will be the case with long running thread. eventually it will move from running to ready after some time and then will resume its works and this cycle will go on till it completes its job. then what is the role of yield? Is it just a voluntary way of moving to ready state to see if anyone need process time ?
Below is the information from https://www.geeksforgeeks.org/java-concurrency-yield-sleep-and-join-methods/ which could not clear my doubt.
yield(): Suppose there are three threads t1, t2, and t3. Thread t1 gets the processor and starts its execution and thread t2 and t3 are in Ready/Runnable state. Completion time for thread t1 is 5 hour and completion time for t2 is 5 minutes. Since t1 will complete its execution after 5 hours, t2 has to wait for 5 hours to just finish 5 minutes job. In such scenarios where one thread is taking too much time to complete its execution, we need a way to prevent execution of a thread in between if something important is pending. yeild() helps us in doing so.
yield() basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should run. Otherwise, the current thread will continue to run.
yield() says to the Java runtime "You may now proceed with another thread". With current operating systems (like Unix or Windwos) which have native threads and preemptive multitasking, a long running thread will be eventually paused for some time and other threads will be executing. With yield() this will possibly happen earlier.
On current environments this functionality is not important in most cases. It is especially useful, if you have only cooperaive multitasking, when there is effectively only one thread and another process can only execute when the current process explictly allows to be paused by calling yield().
sleep() maintains the lock but wait() does not,
my thinking on wait is that it releases the lock as to give other threads a chance to acquire the monitor on that thread while he is waiting.
but having doubt with sleep() why thread maintains the lock while sleeping as it always comes to the runnable state after sleeping
why thread maintains the lock while sleeping as it always comes to the runnable state after sleeping
Consider the below scenario:-
private Object objLock = new Object();
public void myMethod() {
....
synchronized(objLock) {
Thread.sleep(1000); // make the current running thread sleep for 1 second only.
... // Code here which needs to be executed immediately after 1 second sleep time
}
....
}
If at all JVM relesed lock when sleep was called in the above code then when it comes back to runnable state (resumption of execution will depend on scheduling and the availability of processors on which to execute the thread as per JLS Sleep ) your program may not resume at all if another thread by chance took a lock which would make the program behaviour inconsistent. This could be one of the reasons why it doesnot release any locks.
Thread.sleep doesn't have anything to do with locking.
Object.wait needs to be called when holding a lock because the test for the condition to stop waiting needs to be done while holding the lock, in order to have a consistent view of the condition. But usually a thread isn't holding a lock while sleeping.
Sleeping while holding a lock would seem like really bad behavior. But if you need multiple locks, where you acquire one, and have to back off before retrying getting the other, then sleeping while holding a lock might make sense. If calling sleep released locks, this kind of back-off tactic would not work.
Having Thread.sleep be oblivious to locks makes the API simpler and gives the programmer more options (by not totally ruling out its use by a thread that needs to hold onto a lock).
Q: What does Thread.sleep(n) do?
A: NOTHING. Absolutely nothing at all.
Q: How long does it take?
A: At least n milliseconds if the thread is not interrupted.
You don't need to know much else about Thread.sleep().
When I was going through Javadoc for CountDownLatch, I came across a line in the documentation for await method.
If the current count is greater than zero then the current thread
becomes disabled for thread scheduling purposes and lies dormant
What is meant by current thread becomes disabled for thread scheduling purposes here?
On a given system, only a fixed number of threads can actually execute at the same time (you're limited by the number of cores in the machine.) When there are more threads to run than there are cores, the thread scheduler will cycle through the threads in some fashion, giving each a bit of time on the CPU.
However, in some cases it doesn't make sense to give a thread time on the CPU. For example, if a thread acquires a countdown latch whose total is greater than zero, then that thread is stuck waiting for other threads to also acquire the latch. It therefore doesn't make any sense to let that thread have any CPU time, since the thread is just sitting and waiting for other threads. Therefore, typically, the scheduler would not even attempt to give the thread any CPU time, preferring instead to schedule other threads that can still make progress. Once enough threads do acquire the countdown latch, all threads that were blocked this way are then put back into the scheduler for further consideration.
In other words, the thread stops running and the scheduler will intelligently not waste time trying to run it until the latch is ready.
Hope this helps!
It just means that the code in that thread will not go any further until latch.countDown() is called on the same latch from other threads thereby making the latch count 0.
A thread runs when it is in runnable state and the scheduler schedules it. When a threads is disabled for scheduling, it will not get its share of cpu cycles, so it wont run which means its program counter will not increase. Its stack will freeze where it was till it gets the cpu again.
Consider that thread 1 is running following code:
while (true) {
synchronized (this) {
wait();
...Do Something ...
}
}
And lets say we have thread 2 that notifies thread 1, ie:
synchronized (thread1)
thread1.notify();
}
My question is lets say thread 1 got woken up, and is doing something (so its running currently). Then lets say thread2 does notify on thread1 while thread1 is running.
Will thread1 run again when it finishes "do something"? Or will it just sleep instead?
Is my question clear enough?
Thank you.
Say thread 1 got woken up, and is doing something (so its running currently). Then lets say thread2 does notify on thread1 while thread1 is running. Will thread1 run again when it finishes "do something"? Or will it just sleep instead?
The latter. Primitive notify events are delivered to threads that are waiting at the time of the notify / notifyAll call. If no threads are waiting, the notify does nothing: the events are discarded.
Then is it possible to get wait queued? I would like to notify threads when new event happens, but will not like to have threads busy waiting... Is this possible?
Primitive notify events are not and cannot be queued.
If you need notifications to be queued, you will need to use a higher level concurrency class rather than wait / notify. For example Semaphore may do the job ... without busy waiting. Other possibilities are CyclicBarrier and CountdownLatch.
wait() works by purely halting the operation of a thread until another thread notifies it that it can continue running. A synchronized method is one that can only be run by one thread at a time.
A thread won't be 'notified' when it already running.
If a thread is running, and another thread notifies it, then the notify is "wasted" -- it has no effect. If the first thread calls wait() again, it will be returned into the wait pool as normal.
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 ?
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.
a more generic Question would be How are static methods called from different threads ? Won't there be any concurrency problems ?
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 the java.lang.Thread class. Here's a part of its API doc:
Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds, subject to
the precision and accuracy of system timers and schedulers. The thread
does not lose ownership of any monitors.
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 calling Thread.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.
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 called Thread.sleep(). Then it says:
Hey! Nothing to do in this thread (Because I have to wait). I'm going to continue an other Thread.
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:
// here it is 0 millis
blahblah(); // do some stuff
// here it is 2 millis
new Thread(new MyRunnable()).start(); // We start an other thread
// here it is 2 millis
Thread.sleep(1000);
// here it is 1002 millis
MyRunnable its run() method:
// here it is 2 millis; because we got started at 2 millis
blahblah2(); // Do some other stuff
// here it is 25 millis;
Thread.sleep(300); // after calling this line the two threads are sleeping...
// here it is 325 millis;
... // some stuff
// here it is 328 millis;
return; // we are done;