Saturday, February 12, 2011

How to implement Thread in Java ?Example of Runnable interface

How to implement Thread in Java
In my opinion Thread is the most wonderful feature of Java programming language and I remember when I started learning Java in one of programming class in India how important Thread was portrait and how much emphasis given on clear understanding of multi threading. It’s indeed still popular and one of most sought after skill in Java because writing concurrent and multi-threaded application in Java is challenging, despite Java providing excellent support at language level using synchronized and volatile keyword. Main problem with using multiple threads and writing multi-threaded code is issues related to concurrency e.g. deadlock, livelock,  race conditions etc, It takes lot of effort to implement multi-threading correctly in Java application.  In this core java tutorial I will share my experience on different way of implementing Thread in Java; Difference between Thread and Runnable in Java is also a very common core java interview question and asked mostly during junior level java interview.

There are two ways of implementing threading in Java
1) By extending java.lang.Thread class, or
2) By implementing java.lang.Runnable interface.

Before we go into implementation details I just like to cover when we use Thread in Java ? so we use thread if we want some part of code is executed parallel and we put that code inside run() method of either Thread class or Runnable interface.

Actually public void run () method is defined in Runnable interface and since java.lang.Thread class implements Runnable interface it gets this method automatically. I remember by first Java multi threading example which was an animation program where multiple threads were used in Applet to create animation of words falling from top left, middle and top right of the page. That was pretty exciting at that time because till then I only know program which takes input from command prompt and print output on command prompt.


Java Thread Tutorial and Example

How to create Thread in Java - Thread and Runnable classSo now the interview question "Which way of implementing Thread is better? Extending Thread class or implementing Runnable method?
In my opinion implementing Runnable is better because in Java we can only extend one class so if we extend Thread class we can not extend any other class while by implementing Runnable interface we still have that option open with us.

Second reason which make sense to me is more on OOPS concept according to OOPS if we extend a class we provide some new feature or functionality , So if the purpose is just to use the run() method to define code its better to use Runnable interface.

till then we have just created a thread , Thread will not start until you call the start() method of java.lang.Thread class. When we call start () method Java Virtual machine execute run () method of that Thread class into separate Thread other than calling thread. Anybody guess what will happen if we call the run() method directly instead of calling start() method ?

That another popular multi-threading interview question and answer is simple there would be no Error or Exception run() method will simply be executed in the same Thread and new Thread will not be created. Another follow up question would be what will happen if you call start() method twice in same Thread object e.g.


mythread.start();
mythread.start(); //this line will throw IllegalThreadStateException


//implementing Thread by extending Thread class
 public class MyThread extends Thread{      

   public void run(){
      System.out.println(" Thread Running " + Thread.currentThread().getName());
   }
 }


//implementing Thread by implementing Runnable interface

public class MyRunnable implements Runnable{        

    public void run(){
       System.out.println(" Create Thread " + Thread.currentThread().getName());
    }

 }


//starting Thread in Java
Thread mythread = new MyThread(); //Thread created not started
mythread.setName("T1");
Thread myrunnable = new Thread(new MyRunnable(),"T2"); //Thread created      

mythread.start(); //Thread started now but not running
myrunnable.start();


TIP1: It’s not guaranteed that mythread will start before myrunnable it depends upon Thread scheduler.

TIP2: Thread will be said to go on dead state once execution of run() method finished and you can not start that thread again.


Other Java Thread tutorial from Javarevisited Blog

12 comments :

Javin @ Tibco RV Tutorial said...

Hi Sandeep,
Thanks Sandeep. regarding your question can you please clarify what does faster means here , I am not really sure if you talking about class binding or something else ?

Thanks
Javin

Sandeep said...

I meant that extending from class is good in terms of performance or implementing Runnable.
Say I have 50 threads created using Thread class in program1 and 50 using Runnable in Program2. Which is expected to be fast if everything else is same.

Anonymous said...

You should never extend Thread. It's simply a misconception.
Better is to use a ThreadPool with java.util.concurrent.*

Artur Biesiadowski said...

@Sandeep

I cannot imagine anybody asking this question seriously, I suppose that expected answer is something like "I would use Threadpool/Executors in first place"...

CARFIELD said...

I would be surprise if there is performance difference between JUST Runnable or extend Thread, please let me know if it is not.

I guess the question is actually about the possible of using thread pool with same logic.

Javin Paul said...

Hi CARFIELD,

Thread pool is obviously better choice especially when JAVA 5 provides Executor framework and having Runnable task works well with concept of worker threads.

Thanks
Javin

Anonymous said...

can we build 2 thread connected to other in the same calss???????????!!!!111 thanks

Javin @ thread interview questions answers said...

@Anonymous, yes you can have multiple thread started from one Thread. Class is just holder for code and logical representation of Object. What is important is that you can share same Runnable implementation(which is a class ) between multiple threads also.

James said...

Hi Dude, Executor framework which is available from Java 5 onwards is better choice for creating threads and managing them in Java Program Instead of creating threads directly by implementing either Runnable or Callable interface. What is your thought ?

Anonymous said...

in my interface program i am having 2 methods i need to execute only one method how can i execute it

saher said...

what will be the class of Runnble interface

Anonymous said...

WHY DID UUSED INTERFACE IN THREAD?

Post a Comment