In this article we will discuss how to create a thread in Java using Runnable Interface.

Why do we need Runnable Interface

We create threads to execute certain tasks in parallel. Every task is different from another Task. Tasks are usually encapsulated in its own class. Therefore, extending our Task class from Thread is not only an incorrect design decision but also not practical in all scenarios i.e. Java does not support Multiple Inheritance.

Therefore, now we will explore an another way instead of extending Thread class i.e. using Runnable Interface.

Runnable Interface

Thread class need not to know what exactly the task is. It just need to know that how to start the task. For this, an interface is used i.e. Runnable Interface.

Runnable Interface has a run() function and any Task that implements this Interface, has to provide the defination of this run() function

Let’s see a sample Runnable Task i.e.

// Implementing Runnable Interface
class SomeTask implements Runnable {
	// Function that will be called by Thread class after starting
	public void run() {
		System.out.println("SomeTask Task Start");
		// Do some Stuff
		System.out.println("SomeTask Task End");

	}
}

Thread class expects a Task object of Runnable type, so that it can just call the run() function on the Runnable Task object after starting the thread.

Let’s see how to create Thread object by passing a Runnable object in its constructor i.e.

// Creating a Runnable object
Runnable task = new SomeTask();
// Creating a Thread using Runnable object
Thread th1 = new Thread(task);

This way Thread class is not aware of what exactly the Task is. For Thread class, its just an object of Runnable type, and whose run() function contains the code to be executed in this thread.

Checkout complete example as follows,

package com.thispointer.java.thread.examples;

import java.util.concurrent.TimeUnit;

// Implementing Runnable Interface
class SomeTask implements Runnable {
	// Function that will be called by Thread class after starting
	public void run() {
		System.out.println("SomeTask Task Start");
		// Do some Stuff
		System.out.println("SomeTask Task End");

	}
}

public class Example2 {

	public static void main(String[] args) {
		// Creating a Runnable object
		Runnable task = new SomeTask();
		// Creating a Thread using Runnable object
		Thread th1 = new Thread(task);
		// Starting the Thread
		th1.start();

		System.out.println("Hello From Main");
	}
}

Ouput:
Hello From Main
SomeTask Task Start
SomeTask Task End

Its output may vary from system to system. Because, once thread is started using start() function then from that point onwards main() function and run() member function of SomeTask object will run in parallel. Based on context switching order of output can change. Like from output, it seems that main() function printed the “hello From Main” to console before thread could print anything on console.

Join a list of 2000+ Programmers for latest Tips & Tutorials