Thread vs Runnable

Thread is a block of code which can execute concurrently with other threads in the JVM. You can create and run a thread in either ways; Extending Thread class, Implementing Runnableinterface.
Both approaches do the same job but there have been some differences. Almost everyone have this question in their minds: which one is best to use? We will see the answer at the end of this post.
The most common difference is

  • When you extends Thread class, after that you can’t extend any other class which you required. (As you know, Java does not allow inheriting more than one class).
  • When you implements Runnable, you can save a space for your class to extend any other class in future or now.
  • When you extends Thread class, each of your thread creates unique object and associate with it.
  • When you implements Runnable, it shares the same object to multiple threads.

  1)If you want to extend the Thread class then it will make your class unable to extend other classes as java is having single inheritance feature whereas If you implement runnable interface, you can gain better object-oriented design and consistency and also avoid the single inheritance problems.


2)Extending the thread will give you simple code structure in comparison to Runnable Interface.

3)Using Runnable Interface, you can run the class several times whereas Thread have the start() method that can be called only once.




Example:::::

class ImplementsRunnable implements Runnable {
private int counter = 0;
public void run() {
counter++;
System.out.println("ImplementsRunnable : Counter : " + counter);
}
}
class ExtendsThread extends Thread {
private int counter = 0;
public void run() {
counter++;
System.out.println("ExtendsThread : Counter : " + counter);
}
}
public class ThreadVsRunnable {
public static void main(String args[]) throws Exception {
//Multiple threads share the same object.
ImplementsRunnable rc = new ImplementsRunnable();
Thread t1 = new Thread(rc);
t1.start();
Thread.sleep(1000); // Waiting for 1 second before starting next thread
Thread t2 = new Thread(rc);
t2.start();
Thread.sleep(1000); // Waiting for 1 second before starting next thread
Thread t3 = new Thread(rc);
t3.start();
//Creating new instance for every thread access.
ExtendsThread tc1 = new ExtendsThread();
tc1.start();
Thread.sleep(1000); // Waiting for 1 second before starting next thread
ExtendsThread tc2 = new ExtendsThread();
tc2.start();
Thread.sleep(1000); // Waiting for 1 second before starting next thread
ExtendsThread tc3 = new ExtendsThread();
tc3.start();
}
}

  • Coding to an interface rather than to implementation. This makes your software/application easier to extend. In other words, your code will work with all the interface’s subclasses, even ones that have not been created yet.
  • Interface inheritance (implements) is preferable – This makes your code is loosely coupling between classes/objects.(Note : Thread class internally implements the Runnable interface)

However, the significant difference is.
In the Runnable interface approach, only one instance of a class is being created and it has been shared by different threads. So the value of counter is incremented for each and every thread access.
Whereas, Thread class approach, you must have to create separate instance for every thread access. Hence different memory is allocated for every class instances and each has separate counter, the value remains same, which means no increment will happen because none of the object reference is same.
When to use Runnable? Use Runnable interface when you want to access the same resource from the group of threads. Avoid using Thread class here, because multiple objects creation consumes more memory and it becomes a big performance overhead.
Apart from this, object oriented designs have some guidelines for better coding.
Example: coding to an interface.
Map subject = new HashMap();
Assigning HashMap object to interface Map,  suppose in future if you want to change HashMap to Hashtable or LinkedHashMap you can simple change in the declaration part is enough rather than to all the usage places. This point has been elaborately explained.
Which one is best to use?
Ans : Very simple, based on your application requirements you will use this appropriately. But I would suggest, try to use interface inheritance i.e., implements Runnable.



Comments

  1. thank you very much, this is a nice article :)

    ReplyDelete
  2. Sorry, the article looses credibility when I see such obvious problems the author hasn't even taken the trouble to fix... why should I believe him?

    ReplyDelete
    Replies
    1. Which type of credibility and what the problems u r facing?

      Delete
  3. Very good answer. It is one of the most common Java phone screening interview. I used it a lot but few very developer can answer in detail like this. Keep it up.

    ReplyDelete

Post a Comment

Please post comments here:-)

Popular posts from this blog

Android Objective type Question and Answers

Android Questions and Answers for written exams