Multithreading - thread execution methods

We would like to control the execution of thread i.e. prevent/suspend it from execution for some time or alter its execution.

Java provides us with 3 methods to do so :
1. yield()
2. sleep()
3. join()

1. yield()
Threads are executed based on priorities. Now some threads can be less important but may have normal priority. So it should be ok if those threads execute later and some priority thread can finish its execution first. In this scenario, yield() method comes useful.

for(int i=0;i<500; i++) {
    Thread.yield();    System.out.println("Main Thread running");}

When a thread calls the yield() method, it tells the thread scheduler that it can pause its execution and that if there is any other higher priority thread, thread scheduler can give priority to its execution.

2. sleep()
The sleep() method suspends a executing thread for specified time.

MyThread t1 = new MyThread();t1.setName("t1");t1.start();
try {
    Thread.sleep(5000);} catch (InterruptedException e) {
    e.printStackTrace();}

The above code will cause the main thread to sleep for 5 seconds while thread t1 will continue executing.

3. join()
As the name suggests, join() method of a thread joins the end of the thread's execution to its invoking thread's flow. i.e. the caller thread will go into blocking state until the thread finishes its execution.

MyThread t2 = new MyThread();try {
    t2.setName("t2");    t2.start();    t2.join();
    System.out.println("Is thread alive ? : " + t2.isAlive());} catch (InterruptedException e) {
    e.printStackTrace();}


An example showing all the above methods can be found here

Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures