Feb 22, 2016

Why should we prefer java.lang.Runnable over java.lang.Thread?

As most of us are aware of, there are 2 ways to create threads in Java:
- by extending java.lang.Thread class
- by implementing java.lang.Runnable interface

Below are some of the differences between the two ways of creating threads that makes java.lang.Runnable preferable over java.lang.Thread :


1) Limit to extend only one class in java.
In case your class extends Thread class, then your class will not be able to extend any other class as java does not support multiple inheritance. But, if your class implements Runnable interface, then you have an option to extend any other class as well. Also, it makes your code loosely coupled.

2) Overhead of Inherited Methods.
In case your class extends Thread class, then there may be a lot of methods that you do not need which causes additional overhead.

3) Design Practice
In object oriented programming, extending a class means modifying or improving the existing class. If you are not improving the class, then it is not a good practice to extend it. So, implementing Runnable will be the best object oriented design practice.

4) Easy maintainable code
Implementing Runnable interface will make the code easily maintainable as it does a logical separation of task from the runner, which can be either a thread or any executors. Also, it is very easy to modify the task at any time without disturbing the runner. This will make your code loosely coupled and thus improves reusability of the code.

Even Java itself acknowledges this, maybe that’s why Executors accept Runnable as Task and they have worker thread which executes those task.

Example
a) Using Thread Class


public class MainClass
{  
    public static void main(String[] args)
    {
        HelloThread myThread = new HelloThread();
        myThread.start();
    }   
}
 
class HelloThread extends Thread
{
    @Override
    public void run()
    {
         System.out.println("Hello from a thread!!");
    }
}

b) Using Runnable Interface


public class MainClass
{  
    public static void main(String[] args)
    {
        HelloRunnable runnable = new HelloRunnable();
        Thread myThread = new Thread(runnable);
        myThread.start();
    }   
}

class HelloRunnable implements Runnable
{
    @Override
    public void run()
    {
                System.out.println("Inside run method of HelloRunnable!!");
    }
}

Hope you have liked the article. You can join us at +Java Territory to stay updated.

0 comments:

Post a Comment