What is a Thread in Java and How Does It Work with Examples?

What is a Thread in Java and How Does It Work with Examples?

A thread in Java is a lightweight subprocess — the smallest unit of processing. Java enables applications to run multiple threads concurrently, allowing parallel execution and efficient use of system resources. Threading is crucial for tasks like handling multiple user requests, animations, or background operations such as file I/O or data synchronization.

Understanding Threads in Java

Java provides built-in support for multithreading through the java.lang.Thread class and the Runnable interface. Each thread in Java has its own execution path, and the Java Virtual Machine (JVM) handles thread scheduling, switching, and lifecycle management.

Why Use Threads?

  • To perform multiple tasks simultaneously
  • To increase application performance
  • To manage CPU time effectively
  • To build responsive applications

Thread Lifecycle

A thread in Java can be in one of the following states:

  1. New – A thread is created but not yet started.
  2. Runnable – A thread is ready to run and waiting for CPU allocation.
  3. Running – The thread is executing.
  4. Blocked – Waiting for a monitor lock.
  5. Waiting – Thread is waiting indefinitely for another thread to perform a particular action.
  6. Timed Waiting – Waiting for a specified period of time.
  7. Terminated – Thread has completed execution or has been stopped.

Creating a Thread in Java

There are two primary ways to create threads in Java:

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

1. Extending the Thread Class

class MyThread extends Thread {
  public void run() {
    System.out.println("Thread running via Thread class");
  }
}

public class Main {
  public static void main(String[] args) {
    MyThread t1 = new MyThread();
    t1.start();
  }
}
  

2. Implementing the Runnable Interface

class MyRunnable implements Runnable {
  public void run() {
    System.out.println("Thread running via Runnable interface");
  }
}

public class Main {
  public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnable());
    t1.start();
  }
}
  

Thread Methods in Java

  • start() – Starts the execution of the thread
  • run() – Contains the code to be executed in the thread
  • sleep(ms) – Puts the thread to sleep for specified milliseconds
  • join() – Waits for the thread to die
  • interrupt() – Interrupts a sleeping or waiting thread
  • setPriority(int) – Sets priority of thread
  • getPriority() – Returns priority
  • isAlive() – Checks if thread is alive

Thread Priorities

Java threads can be assigned priorities between 1 (MIN_PRIORITY) and 10 (MAX_PRIORITY). Higher priority threads are given preference in scheduling, although it’s not guaranteed due to platform dependency.

Multithreading in Java

Multithreading is the concurrent execution of two or more threads. Java supports multithreading inherently through the Thread class and Runnable interface.

Example of Multithreading

class Task1 extends Thread {
  public void run() {
    for(int i = 1; i <= 5; i++) {
      System.out.println("Task1 - Count: " + i);
    }
  }
}

class Task2 extends Thread {
  public void run() { for(int i = 1; i <= 5; i++) { System.out.println("Task2 - Count: " + i); } } }

public class Main { public static void main(String[] args) { Task1 t1 = new Task1(); Task2 t2 = new Task2(); t1.start(); t2.start(); } } 

Conclusion

Threads in Java enable efficient multitasking, improving application performance and responsiveness. Understanding the lifecycle, methods, and the threading process is essential for writing efficient, concurrent programs. With examples and practical use cases, you can implement threads effectively in Java.

By mastering Java threading, you can elevate your programming skills and tackle complex tasks such as server-side development, real-time applications, and more.

Please follow and like us:

Leave a Comment