MY mENU


Thursday 29 March 2012

Creating Threads in Java

Different ways to Create custom Threads in Java:
in java we can create user defined threads in two ways

  • Implementing Runnable Interface
  • Extending Thread class
in the both two approaches we should override run() method in sub class with the logic that should be executed in user defined thread concurrently, and should call start() method on Thread class object to create thread of execution in java Stacks area.

1. Extending the Thread class.::
class Mythread extends Thread {
                                  //method where the thread execution will start
public void run(){
                             //logic to execute in a thread
}
                               //let’s see how to start the threads
public static void main(String[] args){
Mythread t1 = new Mythread();
Mythread t2 = new Mythread();
t1.start();          //start the first thread. This calls the run() method.
t2.start();         //this starts the 2nd thread. This calls the run() method.
}
}

2. Implementing the Runnable interface.::
class MyRunnable extends Base implements Runnable{
                                      //method where the thread execution will start
public void run(){
                                     //logic to execute in a thread
}
                                    //let us see how to start the threads
public static void main(String[] args){
Thread t1 = new Thread(new MyRunnable());
Thread t2 = new Thread(new MyRunnable());
t1.start();                    //start the first thread. This calls the run() method.
t2.start();                   //this starts the 2nd thread. This calls the run() method.
}
}


In the first approach we create subclass object , Thread class object is also created by using its no-arg constructor. then when start method is called using subclass object custom thread is created in java stacks area, and its execution is started based on processor busy.

In the second approach when we create subclass object , Thread class object is not created, because it is not a subclass of Thread. so to call start method we should create thread class object explicitly by using Runnable parameter constructor, then using this Thread class object we should call start method. Then custom thread is created in Java stacks area and its execution is started based on processor busy.

1 comment:

html5 audio player said...

I have no words for this great post such a awe-some information i got gathered. Thanks to Author.

Post a Comment