Creating a Thread
A Thread can be created in two ways.
- By Extending Thread class
- 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
Post a Comment