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.

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.

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,

Ouput:

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.