Skip to main content

Defining starting thread and 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.

1
2
3
4
5
// 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:

1
2
3
4
5
6
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:

1
2
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:

1
2
3
4
5
6
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:

1
2
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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:

1
2
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.

Comments

Popular posts from this blog

Yahoo! Calendar "Add Event" Seed URL Parameters

I can't seem to find any official documentation on this, so here are my notes. Some information gathered from  http://richmarr.wordpress.com/tag/calendar/ Other information gathered through trial and error, and close examination of the "Add Event" form on Yahoo!'s site. Yahoo! Calendar URL Parameters Parameter Required Example Value Notes v Required 60 Must be  60 . Possibly a version number? TITLE Required Event title Line feeds will appear in the confirmation screen, but will not be saved. May not contain HTML. ST Required 20090514T180000Z Event start time in UTC. Will be converted to the user's time zone. 20090514T180000 Event start time in user's local time 20090514 Event start time for an all day event. DUR value is ignored if this form is used. DUR 0200 Duration of the event. Format is HHMM, zero-padded. MM may range up to 99, and is converted into hours appropriately. HH values over 24 hours appear to be modulated by 24. Durations t...

Java literals:

Java literals:           A constant value which can be assigned to a variable is known as Literal.If we are assigning any outside range value for any data type ,we will get a compile time error saying Possible Loss of Precision found int required byte. For the integral data types (int ,byte,short,long) : we are allowed to specify a literal value in any   one of the following three forms. ---> Decimal literal (normal way) --->Octa literal (prefixed with 0 ) --->Hexa decimal (prefixed with 0x ) int x=10 ------------> Decimal int x=010 ------------>Octa int x=0X10 -------------->Hexa In the Hexa decimal notation for the extra digits we are allowed to specify either small or upper case a,b,c or A,B,C ( this is one of the few places where java is not case sensitive ). Example: class Sample { public static void main(String add[]) { int i = 10; int j=010; int k=0x10; System.out.println( i+”….”+j...