Threads

A thread is a lightweight process, the smallest unit of execution. It allows for concurrent execution of code within a program, enabling multitasking and efficient use of CPU resources. A thread is an instance of the Thread class or an implementation of the Runnable interface. A single Java program can have multiple threads running at the same time, each performing a different task or part of a task. This parallel execution of threads makes Java programs more efficient, especially when performing tasks such as I/O operations, computations, or network communication.

Each thread has its own program counter, stack, and local variables, but shares memory resources (such as heap memory) with other threads in the same process. This means threads can communicate with one another and share data, but also requires mechanisms for managing concurrent access to shared resources, such as synchronization and locks. Java supports multithreading, which means multiple threads can run simultaneously, sharing the same process’s resources but executing independently.

For example, in a web browser

  • One thread handles UI interactions.
  • Another thread downloads data.
  • Another thread renders content.

Each task runs concurrently, enhancing performance.

Types of Threads in Java

Java provides two types of threads:

User Threads

  • Created explicitly by the programmer.
  • Runs independently and continues execution until completion.

Daemon Threads

  • Runs in the background (e.g., garbage collection).
  • Terminates when all user threads finish execution.

Implementation

Creating a Thread by Extending the thread Class

  • The MyThread class extends Thread.
  • The run() method defines what the thread will do.
  • The start() method begins execution of the thread.

Running Multiple Threads

  • Two threads (t1 and t2) run simultaneously.
  • Thread.sleep(500) makes the thread pause for 500 milliseconds.

Benefits of Using Threads

  • Improves performance by utilizing CPU efficiently.
  • Enables parallel execution of tasks.
  • Enhances responsiveness in applications (e.g., UI interactions).
  • Efficient resource sharing within the same process.