27 May 2013

How Many Ways We Can Create Threads In Java

In java there are only 2 ways of creating threads. How ever since java1.5 there is one another way to invoke a Thread. The following shows how we can create threads in java.

First Method:-

A class can extend Thread class and overrides the run method of the Thread class.

Example:- 

 public class Murali extends Thread{
     public void run(){
     ==do something here==
    }
  }//class ends here.
Murali a=new Murali();
a.start();

Second Method:-

Writing a custom class which implements Runnable interface and pass this class to the Thread constructor.

Example:-      

 public class Car implements Runnable{
   public void run(){
    ==do something here==
   }
  }

Thread a=new Thread(new Car());
a.start();

Second method is good than first method because only one class can be extended and if you have extended Thread class no other class can be extended.
Since java1.5:-

How ever since java1.5 there is another way to invoke a thread. That is by “ExecutorService”. All these classes are from the “java.util.concurrent” package. There are various ways to create a “ExecutorService” using “Executors” factory class. The following is one of the way to create “ExecutorService”..

ExecutorService es= Executors.newSingleThreadExecutor();
RunnableImpl r = new RunnableImpl();
Future fu=es.submit(r);

using “ExecutorService” methods we can submit eighter Runnable or Callable to the service for execution.

How ever this cannot be said as the new way to create a Thread. It is because ExecutorService internally uses “ThreadFactory” class to create a new thread which internally uses eighter first or second method. So we have to say that there are only two ways to create threads but there is a new way in java1.5 to invoke a thread but not to create a Thread.
Post a Comment