Friday 3 May 2013

How to implement Thread in Java ?Example of Runnable interface

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

How HashMap works in Java?

Why wait and notify method must be called in synchronized context?

10 practical tips on Java debugging with eclipse

How Synchronization works in Java?

How Classpath works in Java?
Why wait and notify are declared in Object class and not in Thread class
How to write Thread-safe class in Java

Please share with your friends if like this article

No comments:

Post a Comment