create thread in multi threading

How to create thread

There are two ways to create a thread:
  1. By extending Thread class
  2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface.

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run().
  1. public void run(): is used to perform action for a thread.

Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs following tasks:
  • A new thread starts(with new callstack).
  • The thread moves from New state to the Runnable state.
  • When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class

  1. class Multi extends Thread{  
  2. public void run(){  
  3. System.out.println("thread is running...");  
  4. }  
  5. public static void main(String args[]){  
  6. Multi t1=new Multi();  
  7. t1.start();  
  8.  }  
  9. }  


2) Java Thread Example by implementing Runnable interface

  1. class Multi3 implements Runnable{  
  2. public void run(){  
  3. System.out.println("thread is running...");  
  4. }  
  5.   
  6. public static void main(String args[]){  
  7. Multi3 m1=new Multi3();  
  8. Thread t1 =new Thread(m1);  
  9. t1.start();  
  10.  }  
  11. }  

Comments