How to create thread in Java

Posted on Updated on

A thread can be created by instantiating the object of type Thread.

There are two ways defined by which thread can be created.

  1. By implementing the Runnable interface
  2. By extending the Thread class

Implementation of Thread by Runnable interface:

To create a thread, we must create a class which implements Runnable interface, which is abstract of executable codes. A thread can be created on an object which implements Runnable(). In order to implement Runnable, one need to implement only run() method as mentioned below.

  • public void run()

The run class behaves same as main thread class. It includes code which constitutes the new thread. It can call other classes, methods and also declare variable. The only difference is run establishes the entry point for other thread or concurrent threads and terminated when it is returned.

Post creation of class which implemented Runnable, one need to instantiate an object of type Thread from within that class. Thread defines several constructor, the one used is displayed here-

  • Thread(Runnable threadObj, String threadname)

Here threadObj is the instance of class which implemented Runnable interface. This is used to define where the execution of thread will begin. The threadname is  name of thread that will be started.

The thread will not start executing until you call its start() method, which is declared within Thread. Here start() basically executes a call to run(), as mentioned below.

  • void start()

Let us see an example to understand better

Output

Implementation of Thread by extending Thread class:

The another method by which Thread can be created is by extending Thread class and then create the instance of it. The class extending Thread class must override run() method and must call start() method to start executing the Thread.

Let us see an example to understand better-

Output

There is an obvious question that out of two ways explained, which one is better.

When a thread is being created by extending Thread class, then all the methods declared in Thread class can be overridden but only run() method is required to be overridden. In case of implementation of Runnable interface, only run() method can be overridden. Now it depends upon programmer to select which approach is suitable.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.