There are two ways of implementing threading in Java
1) By extending java.lang.Thread class, or
2) By implementing java.lang.Runnable interface.
mythread.start();
mythread.start(); //this line will throw IllegalThreadStateException
//implementing Thread by extending Thread class
public class MyThread extends Thread{
public void run(){
System.out.println(" Thread Running " + Thread.currentThread().getName());
}
}
//implementing Thread by implementing Runnable interface
public class MyRunnable implements Runnable{
public void run(){
System.out.println(" Create Thread " + Thread.currentThread().getName());
}
}
//starting Thread in Java
Thread mythread = new MyThread(); //Thread created not started
mythread.setName("T1");
Thread myrunnable = new Thread(new MyRunnable(),"T2"); //Thread created
mythread.start(); //Thread started now but not running
myrunnable.start();
Actually public void run () method is defined in Runnable interface and since java.lang.Thread class implements Runnable interface it gets this method automatically.
Thread will not start until you call the start() method of java.lang.Thread class. When we call start () method Java Virtual machine execute run () method of that Thread class into separate Thread other than calling thread