Java Start Thread
We can start a Java thread programmatically by calling the start method of Java Thread Class.But,Initiating the Java Thread Class object can be done in two ways.
- Extending the Thread class
- Implementing the Runnable interface
Thread Class Example with extends
public class CreationOfThread extends Thread { public static void main(String[] args) { Thread thread=new CreationOfThread(); thread.start(); } public void run() { System.out.println("New thread started Running"); } }
Thread Class Example with Runnable Interface
public class CreationOfThread implements Runnable { public static void main(String[] args) { CreationOfThread cot=new CreationOfThread(); Thread thread=new Thread(cot); thread.start(); } public void run() { System.out.println("New thread started Running"); } }
In the above example, we are implementing the Runnable interface and creating the Object of CreationOfThread class, And passing the Object of the CreationOfThread class to the Thread class constructor.After that we are starting a thread.