Search This Blog

Thursday, 8 November 2012

why two way exist to implement thread in java ?

Java has great concept called Thread. Thread is most discussed and assume to be most difficult  concept by people. while creating a simple thread, Java provide two ways

1) Extends Thread class 

public class Method1 extends Thread {

 public static void main(String[] args) {
  Method1 tm = new Method1();
  Thread th = new Thread(tm);
  th.start();
 }

 @Override
 public void run() {
  super.run();
  System.out.println("Extends Thread to create a Thread :)");
 }
}

2) Implement Runnable interface

public class Method2 implements Runnable {

 public static void main(String[] args) {
  Method2 tm = new Method2();
  Thread th = new Thread(tm);
  th.start();
 }

 @Override
 public void run() {
  System.out.print("Implement Runnable interface to create a Thread");
 }
}

So doubt goes increasing for a new programmer. Two ways to doing same thing ? why these necessity exists Let them clarify

Noted : Java provide inheritance . So we can use on class property inside another class by extending class. Consider class MN has method addSum(), iNeedMn want to use this addSum() then simple iNeedMn extends MN is solution. This is called single inheritance

    public class MN{
       
        public void addSum(){
            System.out.print("From MN");
        }
    }
   
    public class iNeedMn extends MN{
        @Override
        public void addSum() {
            super.addSum();
        }
    }

Consider now iNeedMn want to access the property of Thread class also (So called multiple Inheritance(is not allowed in JAVA) i.e one class can extends any number of class) or say iNeedMn need to be use as Thread somewhere. Impossible ???

Cause of providing two to make a thread is to avoid impact of banned multiple inheritance.We can not extends two classes but we can implement any number of interface

Which way to prefer ?

Implementing Runnable is preferred way.It's generally discouraged to extend the Thread class. The Thread class has a lot of overhead and the Runnable interface doesn't   

No comments:

Post a Comment

Feedback always help in improvement. If you have any query suggestion feel free to comment and Keep visiting my blog to encourage me to blogging

Android News and source code