Code Pumpkin

Defining and Starting a Thread | Thread VS Runnable

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.

That's all for this topic. If you guys have any suggestions or queries, feel free to 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 🙂

If you like the content on CodePumpkin and if you wish to do something for the community and the planet Earth, you can donate to our campaign for planting more trees at CodePumpkin Cauvery Calling Campaign.

We may not get time to plant a tree, but we can definitely donate ₹42 per Tree.



About the Author


Surviving Java Developer, Passionate Blogger, Table Tennis Lover, Bookworm, Occasional illustrator and a big fan of Joey Tribbiani, The Walking Dead and Game of Thrones...!!



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 Posts : 124
follow us in feedly

Like Us On Facebook