Friday, 24 January 2014

CREATING A THREAD

CREATING AND STARTING THREADS IN JAVA

What are the two different methods of creating a thread in Java? What method must be implemented in either case?


In Java, an object of the Thread class can represent a thread. Thread can be implemented through any one of two ways:

                          1.You can implement the Runnable interface.
                          2.You can extend the Thread class itself.



1.CREATE THREAD BY EXTENDING THREAD:


For creating a thread a class have to extend the Thread Class. For creating a thread by this procedure you have to follow these steps:


1.Extend the java.lang.Thread Class.
2.Override the run( ) method in the subclass from the Thread class to define the code executed by the thread,which is declared like this:
                                                            public void run()
3.Create an instance of this subclass. This subclass may call a Thread class constructor subclass constructor.
4.Invoke the start( ) method on the instance of the class to make the thread eligible for  running .The start method is shown here,
                                                          void start()

Example:
Demonstrates a single thread creation extending  the "Thread" Class:

class MyThread extends Thread{
  String s=null;
  MyThread(String s1){
  s=s1;
  start();
  }
  public void run(){
  System.out.println(s);
  }
}
public class RunThread{
  public static void main(String args[]){
  MyThread m1=new MyThread("Thread started....");
 }
}


Output:

Thread started....


1.CREATE THREAD BY IMPLEMENTING RUNNABLE:


The procedure for creating threads by implementing the Runnable interface is as follows:

1.A Class implements the Runnable Interface, override the run() method  to define the code executed by thread. An object of this class is Runnable Object.
2.Create an object of Thread Class by passing a Runnable object as argument.
3.Invoke the start( ) method on the instance of the Thread class.
The following program demonstrates the thread creation implenting the Runnable interface:

Example:

  class MyThread1 implements Runnable
{
Thread t;
String s=null;
MyThread1(String s1)
{
 s=s1;
t=new Thread(this);
t.start();
}
public void run()
{
System.out.println(s);
}
}
  public class RunableThread
{
public static void main(String args[]) 
{
MyThread1 m1=new MyThread1("Thread started....");
}
}



Output:

Thread started....







No comments:

Post a Comment