We can define and implement a thread in java using TWO ways:
Extending the Thread class
class InterviewBitThreadExample extends Thread{ public void run(){ System.out.println("Thread runs..."); } public static void main(String args[]){ InterviewBitThreadExample IB = new InterviewBitThreadExample(); ib.start(); } }
Implementing the Runnable interface
class InterviewBitThreadExample implements Runnable{ public void run(){ System.out.println("Thread runs..."); } public static void main(String args[]){ Thread ib = new Thread(new InterviewBitThreadExample()); ib.start(); } }
Implementing a thread using the method of Runnable interface is more PREFERRED and advantageous as Java does not have support for multiple inheritances of classes.
start() method is used for creating a SEPARATE call stack for the thread execution. Once the call stack is created, JVM calls the run() method for executing the thread in that call stack.