Creating a Thread


A Thread can be created in two ways.
  1. By Extending Thread class
  2. By Implementing Runnable interface



Examples

1. Creating a Thread by extending 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....");
 }
}





2. Creating a Thread by implementing Runnable interface


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....");
  }
}



Comments

Popular posts from this blog

OOPS Concepts with realtime examples

What is an interface?

Asynchronous Messaging