☕ Java Q17 / 105

What is a Thread in Java?

AI-Powered Answer ✓ Answered

In Java, a thread is a lightweight subprocess, the smallest unit of processing. It allows a program to perform multiple operations concurrently, leading to more efficient utilization of CPU resources and improved responsiveness. Each thread runs independently within a single process, sharing the same memory space but having its own call stack.

What is a Thread?

A thread represents an independent path of execution within a program. Unlike a process, which is a heavyweight execution unit with its own memory space, a thread is a lightweight component that shares resources like memory and open files with other threads belonging to the same process. This shared memory allows for easier communication between threads.

Key Characteristics

  • Concurrency: Allows multiple parts of a program to execute simultaneously.
  • Shared Memory: All threads within a process share the same heap memory, making data sharing straightforward.
  • Independent Execution: Each thread has its own program counter, stack, and local variables.
  • Overhead: Creating and managing threads incurs less overhead compared to processes.

Lifecycle of a Thread

A Java thread goes through various states from its creation to termination. The Thread.State enum defines these states, which describe the current activity of a thread.

  • NEW: A thread that has not yet started.
  • RUNNABLE: A thread executing in the JVM or waiting for the CPU.
  • BLOCKED: A thread that is blocked waiting for a monitor lock.
  • WAITING: A thread that is waiting indefinitely for another thread to perform a particular action.
  • TIMED_WAITING: A thread that is waiting for another thread to perform an action for a specified waiting time.
  • TERMINATED: A thread that has exited.

Creating Threads in Java

Java provides two primary mechanisms for creating threads:

1. Extending the `Thread` class

In this approach, you create a class that extends java.lang.Thread and override its run() method. The run() method contains the code that the thread will execute. To start the thread, you create an instance of your class and call its start() method.

java
class MyThread extends Thread {
    public void run() {
        System.out.println("Thread extending Thread class is running.");
    }
    public static void main(String[] args) {
        MyThread t = new MyThread();
        t.start(); // Invokes the run() method
    }
}

2. Implementing the `Runnable` interface

This is generally the preferred approach, especially when your class already needs to extend another class. You create a class that implements the java.lang.Runnable interface and define the thread's execution logic within its run() method. An instance of this Runnable is then passed to a Thread constructor, and start() is called on the Thread object.

java
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Thread implementing Runnable interface is running.");
    }
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.start(); // Invokes the run() method of MyRunnable
    }
}

Common Thread Methods

MethodDescription
`start()`Causes this thread to begin execution; the JVM calls the `run()` method.
`run()`Contains the code that is executed by the thread.
`sleep(long millis)`Causes the currently executing thread to cease execution for a specified number of milliseconds.
`join()`Waits for this thread to die.
`interrupt()`Interrupts this thread.
`yield()`Causes the currently executing thread object to temporarily pause and allow other threads to execute.
`setName(String name)`Changes the name of this thread.
`getName()`Returns the name of this thread.
`getId()`Returns the identifier of this thread.
`isAlive()`Tests if this thread is alive.