Sleep() method:
Sleep is a static method of the Thread class. That means you can’t stop the thread by it’s instance. Calling the sleep method puts the current thread into sleep mode.
The sleep() method slows down the thread and moves it into sleep. Thread won’t be in either running/ runnable state.
Once it wakes up it goes to runnable state.
Guarantees to stop the current running thread for the specified milliseconds but again no guarantee for the order of execution.
Syntax:
try {
Thread.sleep(5*60*1000); // Sleep for 5 minutes
} catch (InterruptedException ex) { }
Calculator Example
package thread;
/**
* @author Sivaranjani D
*/
public class SleepMethod {
public static int total;
public static void main(String[] args) {CalculateSum calculator = new CalculateSum();
calculator.start();
/**
* Turn this sleep on and off to see the usefulness of sleep method
*/
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("The sum of first 100 Numbers : "+total);
}}
class CalculateSum extends Thread{
@Override
public void run() {
for(int i=0;i<100;i++){
SleepMethod.total=SleepMethod.total+i;
}}}
Output: The sum of first 100 Numbers : 4950
yield() method
Yield() method is closely related with thread priorities. So first will see what is priorities in thread.
Thread priorities
Threads usually run with some priorities usually from 1-10 (Some JVM’s use lesser than 10 also)
Most JVM’s schedule the thread based on thread priorities. But again keep in mind that we can't control the order of thread execution.
In java thread priority can be set by,
Thread thread = new Thread();
thread.setPriority(6);
thread.start();
Also Thread provides the following three static final fields
- Thread.MIN_PRIORITY (1)
- Thread.NORM_PRIORITY (5)
- Thread.MAX_PRIORITY (10)
Why yield is required?
As we know nothing is guaranteed why need to use yield?
This just a hint to the Processor that current thread is willing to give up it’s CPU usage. If there are lot's over CPU utilizing threads, this method will help them to share the time between the threads and thus increases the overall performance of the application.
Summary
- Thread.yield() is a static method like sleep method.
- In the priority based scheduling if many threads are with the same priority, then other same priority threads will not get a chance to executes until the current thread finishes.
- yiled is used for turn taking between equal priority and heavy CPU utilizing threads.
Join () method
join() method is a non-static method.The currently running thread will be joined at the end of the thread instance referenced by this method.
For example, Consider ThreadA is currently in running state. Calling the below code,
ThreadB thread=new ThreadB();
thread.start();
thread.join();
Moves ThreadA to runnable state and makes threadA to wait untill ThreadB completes.
[caption id="attachment_488" align="aligncenter" width="770"]

No comments:
Post a Comment