Threads (Runnable vs Thread)

1.What is Thread?

A thread in Java is nothing but an instance of class which is running independently to complete its job.
Thread is created in Java with the help of java.lang.Thread class, and hence it is controlled using the same class.

Threads executes parallel without waiting for main program/each other and completes its job, unless we make it interact with each other for some logical purpose or sharing some common resources.

Multiple threads running in an application and interacts with each other to complete a common goal is called multi-threading.

When threads are running in parallel, thread executes on priority. Every thread has its own priority. High priority threads will be executed before the low priority threads.

Threads can be created in Java in 2 ways.

  1. By extending the Thread class
  2. By Implementing Runnable Interface

1.1 Extending Thread Class:

Anybody can create their own thread class by extending this Thread.java class.

The run() method of Thread class needs to be overridden to implement our functionality of the Thread.

Hence user can implement the own functionality of thread by writing the logic in the overridden run() method.

Thread can be executed by calling the start() method in the Thread which is present in the Thread.java class.

We could in the example, threads are executing parallel of its own independently not waiting for each other. Hence the result is printed whenever thread is called and executed., and not waiting for other.

Result:

1.2 Implementing Runnable Interface:

Thread can also created by implementing Runnable interface.

Runnable interface run() method is called inside a run() method of thread.

Hence object implements Runnable interface will be passed as a argument to a Thread object.

When the Thread object run() method is invoked, the run() method we implemented for the Runnable interface in our object will be invoked. Hence thread will be started.

We could in the example, threads are executing parallel of its own independently not waiting for each other. Hence the result is printed whenever thread is called and executed., and not waiting for other.

Result:

Leave a Reply

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