We can create thread by two methods:
1.By extends
2.By implements.
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[]){
ByExtends t1=new ByExtends(); //Create object of ByExtends class
t1.start(); //start thread
}
}
public class ByImplements implements Runnable {
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
ByImplements m1=new ByImplements();
Thread t1 =new Thread(m1); //passing class object in thread
t1.start(); //start thread
}
}
1.By extends
2.By implements.
Example:
class ByExtends extends Thread{public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[]){
ByExtends t1=new ByExtends(); //Create object of ByExtends class
t1.start(); //start thread
}
}
Example:
public class ByImplements implements Runnable {
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
ByImplements m1=new ByImplements();
Thread t1 =new Thread(m1); //passing class object in thread
t1.start(); //start thread
}
}
Multiple Thread:
Example:
public class MultipleThread implements Runnable{
public void run(){
System.out.println("The current Thread = "+Thread.currentThread().getName());
}
}
class Multithread{
public static void main(String[] args) {
MultipleThread mThread=new MultipleThread();
Thread t1=new Thread(mThread);
Thread t2=new Thread(mThread);
Thread t3=new Thread(mThread);
t1.start();
t2.start();
t3.start();
}
}
public void run(){
System.out.println("The current Thread = "+Thread.currentThread().getName());
}
}
class Multithread{
public static void main(String[] args) {
MultipleThread mThread=new MultipleThread();
Thread t1=new Thread(mThread);
Thread t2=new Thread(mThread);
Thread t3=new Thread(mThread);
t1.start();
t2.start();
t3.start();
}
}