Tech Master Tutorials
Email Facebook Google LinkedIn Pinterest Twitter
Home Java Java 8 Java Interview Questions Java8 Interview Questions Object Oriented Programming in Java JVM Java Programming

Thread Creation

Thread can be created using following ways :

  • Extending Thread Class
  • Implementing Runnable Interface

Extending Thread class:
Below is the thread implementation by sub classing the Thread class. Thread class implements the runnable interface which is a functional interface that provides run() method. Thread class overrides the run method also provides various other methods of its own. While creating a thread by extending the Thread class, the executable code need to be written in the run method. Thread provides amethod start, calling upon start thread will provide itself for execution. This stage of the thread lifecycle is called runnable. After the call to Start() method thread will go in the runnable state. After calling the start() method when will the be running that is unpredictable and will depend on the operating system’s mechanisms. Whenever the thread will get the chance to run, run() method will be executed and the code inside it or through any method call.

public class ThreadTest extends Thread{
	@Override
	public void run() {
		System.out.println("Thread running ....");
		for (int i = 0; i < 5; i++) {
			System.out.println(i);
		}
	}

	public static void main(String[] args) {
		ThreadTest threadObj=new ThreadTest();
		threadObj.start();
	}
}

Using Runnable interface:
As mentioned above in the previous section, runnable interface provides only a single method that is run() mthod. A class can implement the runnable interface and provide the definition for the run() method. And then implementing class can be passed to the Thread class object using one of its constructors that accepts a Runnable class. Runnable interface will force to provide the definition for run() method. Following code demonstrates the creation of a thread using runnable.

public class RunnableTest implements Runnable{

	@Override
	public void run() {
		System.out.println("Thread running ....");
		for (int i = 0; i < 5; i++) {
			System.out.println(i);
		}
	}
	
	public static void main(String[] args) {
		//Creating a runnable instance
		RunnableTest runnableObj=new RunnableTest();
		
		//Creating an instance of Thread class and passing the runnable instance to the Thread object 
		Thread threadObj=new Thread(runnableObj);
		threadObj.start();
	}

}