Code Pumpkin

Defining and Starting a Thread | Thread VS Runnable

Subscribe

Java threads are objects like any other Java objects. Threads are instances of class java.lang.Thread, or instances of subclasses of this class. In addition to being objects, java threads can also execute code.

Creating and Starting Threads

Here is the code to create a Thread and start its execution.


// Creates Thread Object
Thread thread = new Thread();  

// Starts Thread execution
thread.start();

This example doesn't specify any code for the thread to execute. The thread will stop right away after it is started.

There are two ways to specify what code the thread should execute.

  1. To create a subclass of Thread and override the run() method.
  2. To implement a Runnable(java.lang.Runnable) interface, override its  run() method and pass that Runnable object to the Thread constructor.

Thread Subclass

The first way to specify what code a thread is to run, is to create a subclass of Thread and override the run() method. The run() method is what is executed by the thread after you call start(). Here is an example of creating a Java Thread subclass:


  public class MyThread extends Thread {

    public void run(){
       System.out.println("MyThread is running");
    }
  }

To create and start the above thread you can do like this:


  MyThread myThread = new MyThread();
  myTread.start();

The start() call will return as soon as the thread is started. It will not wait until the run() method is done. The run() method will execute as if executed by a different CPU.

The above example would print out the text "MyThread is running".


Runnable Interface Implementation

The second way to specify what code a thread should run is by creating a class that implements java.lang.Runnable. The Runnable object can be executed by a Thread.

Here is a Java Runnable example:


  public class MyRunnable implements Runnable {

    public void run(){
       System.out.println("MyRunnable is running");
    }
  }

To have the run() method executed by a thread, pass an instance of MyRunnable to a Thread in its constructor. Here is how that is done:


   Thread thread = new Thread(new MyRunnable());
   thread.start();

When the thread is started it will call the run() method of the MyRunnable instance instead of executing it's own run() method. The above example would print out the text "MyRunnable is running".


Thread VS Runnable

Runnable:
When we implement Runnable interface , it means we are creating something which is run able in a different thread. Creating something which can run inside a thread (runnable inside a thread), doesn't mean to creating a Thread.
So the class MyRunnable is nothing but a ordinary class with a void run() method. And it's objects will be some ordinary objects with only a method run() which will execute normally when called. (unless we pass the object in a thread).

Thread:
Thread class is a very special class with the capability of starting a new Thread which actually enables multi-threading through its start() method.

In short, 

  • Runnable : Something that can run inside a Thread.
  • Thread : Something That can start a new Thread.

So technically and theoretically both of them is necessary to start a thread, one will run and one will make it run in new thread.


extending Thread VS implementing Runnable

There has been a good amount of debate on which is better way to create and start a thread. Both approaches have their pros and cons and there is a situation when extending Thread is logical but in most cases implementing Runnable is the better option. Let's see the difference between both the approaches.

  1. Java doesn't support multiple inheritance, which means you can only extend one class. When you extends Thread class,  you can’t extend any other class.  But when you implements Runnable, your class can extend any other class.

  2. In Object oriented programming extending a class generally means adding new functionality, modifying or improving behaviors. If we are not making any modification on Thread then use Runnable interface instead.

  3. In other words, if you are extending Thread class just for run() method , you will also get overhead of all other methods of Thread class.  Inheriting all Thread methods are additional overhead just for representing a Task which can be done easily with Runnable.

  4. So, if your goal is to just write some code in run() method for parallel execution then use Runnableinstead of extending Thread class.  

  1. You can not start a thread with Runnable , you need to pass it to a instance of Thread. But it is possible to create and run a thread only by using Thread class because it implements Runnable.

  2. Runnable interface represent a Task which can be executed by either plain Thread or Executors. so logical separation of Task as Runnable and Thread is good design decision.

  3. By extending Thread, each of your threads has a unique object associated with it, whereas by implementing Runnable, many threads can share the same runnable instance  e.g.


public class ThreadVsRunnableDemo {

    public static void main(String[] args) {

        MyRunnable r = new MyRunnable();
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        t1.start();
        t2.start();

    }
}

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("MyRunnable is running");
    }
}

Output:


MyRunnable is running
MyRunnable is running
extending Thread impementing Runnable
1 You cannot extend any other class. You can extend another class
2 Task and Runner are tightly coupled Task and Runner are loosely coupled
3 Overhead of additional methods of Thread class. No overhead of additional methods
4 Can not be used with executor service. Can be used with executor service.
5 Maintenance of code is not easy. Maintenance of code is easier.

Happy Learning..!! smiley

That's all for this topic. If you guys have any suggestions or queries, feel free drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here

Happy Learning 🙂


Further Reading For interview Preparation

  1. Inter thread communication using wait(), notify() and notifyAll()  methods
  2. interrupt(), interrupted() and isInterrupted() 
  3. InterruptedException
  4. String Pool
  5. interface VS abstract class
  6. Wrapper Classes – Autoboxing and Unboxing,  IntegerCache and Immutability
  7. How To Create Immutable Class In Java
  8. CountDownLatch Vs CyclicBarrier
  9. What is the use of private constructor in java?

Tags: , , , ,


Comments and Queries

If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> 
String foo = "bar";
</code></pre>
For more information on supported HTML tags in disqus comment, click here.

Total Post : 80
Subscribe
Contribute Your Articles

Interview Experiences

Related Books

Like Us On Facebook

Alexa Page Rank