Creating a Thread

we can create Thread by instantiating and object of type Thread. Java defines two ways by which we can create a Thread :
1. By implementing the runnable interface
2. By extending the Thread class.

implementing the runnable interface

Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable example:

public class example4 implements Runnable { // implementing runnable interface

	public void run() {
		System.out.println("Hello from a thread!");
	}

	public static void main(String[] args) {
		Thread T1 = new Thread(new example4()); // thread object of class
												// example4
		T1.start(); // will execute run method of example4;

	}
}

Extending the Thread Class

Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the below example:

public class HelloThread extends Thread { // extending Thread class

    public void run() {
        System.out.println("Hello from thread 2");
    }

    public static void main(String args[]) {
    	Thread t2 = new Thread(new HelloThread());
        t2.start();
    }
}