Tuesday, December 13, 2011

What is a thread? and how to create a thread in java?

Thread: A thread is a light weight process. It represents execution of statements. Threads are called light weight because they utilize minimum resources of the system.

How to create a Thread:
Threads can be created in two ways.
 1. By inheriting from thread class
 2. By using runnable interface
1.By inheriting from thread class:

class Mythread extends Thread
{
    public void run()
   {
       for(int i=0;i<1000;i++)
      {
         System.out.println((i);
      }
   }
}
class demo
{
public static void main(String args[])
{
Mythread obj=new Mythread();
Thread t=new Thread(obj);
t.start();
}
}

             In the above example, Thread is created using Thread object_name=new Thread(class_object) statement. After creating a thread, we invoke thread by calling start() method. Then run() method starts execution when start()  method is called. A thread is terminated when it comes out of run() method.

2. By using runnable interface:

class Mythread implements Runnable
{
    public void run()
   {
       for(int i=0;i<1000;i++)
      {
         System.out.println((i);
      }
   }
}
class demo
{
public static void main(String args[])
{
Mythread obj=new Mythread();
Thread t=new Thread(obj);
t.start();
}
}