DEV Community

Sonali Gupta
Sonali Gupta

Posted on

How to create a new Thread in java ?

We are going to explore different ways to start a thread & execute parallel tasks.

This is very useful, in particular when dealing with the long or recurring operations that can't run on the main thread or where the UI interaction can't be put on hold while waiting for results or response.

Running a Thread

  1. By Extending the Thread class

Define the task class which will perform a task on different thread. The class should extends Thread class & override the run method to define the task to execute on a separate thread.

image

And now we write a second class to initialize and start our thread:

image

We should call the start() method on threads in the NEW state (the equivalent of not started). Otherwise, Java will throw an instance of IllegalThreadStateException exception.

The output will be :
image

Now, let us assume you want to start multiple threads:

image

The output will be :
image

  1. Implementing the Runnable Interface

Define a class which will implements the Runnable Interface. The Runnable interface is also a functional interface, which has only 1 method i.e run.

image

image

The output will be:
image

If you are not extending the Thread class,your class object would not be treated as a thread object.So you need to explicitely create Thread class object.We are passing the object of your class that implements Runnable so that your class run() method may execute.

Thanks :)

keep-learning :)

Top comments (0)