Home Java Tutorial Threads in Java

Threads in Java

by anupmaurya
11 minutes read

In this tutorial, you’ll learn about Threads in Java, Why thread is used in Java, Java Thread Benefits and How to create a thread in Java, and more.

What is Thread?

A thread is a lightweight subprocess, the smallest unit of processing or we can say that a thread is a series of executed statements .The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

Why thread is used in Java?

We use Threads to make Java application faster by doing multiple things at the same time. In technical terms, Thread helps you to achieve parallelism in Java programs

Java Thread Benefits

  1. Java Threads are lightweight compared to processes, it takes less time and resource to create a thread.
  2. Threads share their parent process data and code
  3. Context switching between threads is usually less expensive than between processes.
  4. Thread intercommunication is relatively easy than process communication.

Creating a Thread

There are two ways to create a thread.

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

It can be created by extending the Thread class and overriding its run() method:

public class Main extends Thread {
  public void run() {
    System.out.println("This code is running in a thread");
  }
}

Another way to create a thread is to implement the Runnable interface:

public class Main implements Runnable {
  public void run() {
    System.out.println("This code is running in a thread");
  }
}

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.