java.lang.Thread

About

The java.lang.Thread class is the foundation for multithreading in Java. It represents an individual thread of execution and provides methods for managing thread behaviour, controlling execution, and retrieving thread information.

The Thread class allows:

  • Creating and controlling threads

  • Managing thread lifecycle (start, sleep, join, etc.)

  • Setting thread properties (priority, daemon, etc.)

  • Handling exceptions within threads

Declaration

public class Thread implements Runnable
  • The Thread class implements the Runnable interface, allowing it to execute tasks.

Why Is Thread Not Abstract?

Although Thread is often subclassed, Java does not enforce it as an abstract class because:

  1. Direct Instantiation: Java allows us to create a Thread instance with a Runnable directly.

    Thread t = new Thread(() -> System.out.println("Running"));
    t.start();
  2. Default Implementation of run(): Thread provides a default empty implementation of run():

    public void run() { }

    If Thread were abstract, every subclass would be forced to implement run(), which is not always necessary.

Constructors

The Thread class provides multiple constructors to create threads.

Constructor

Description

Thread()

Creates a new thread with a default name.

Thread(Runnable target)

Creates a thread that executes a Runnable task.

Thread(Runnable target, String name)

Creates a thread with a specific name.

Thread(String name)

Creates a thread with a given name.

Thread(ThreadGroup group, Runnable target)

Creates a thread in a specific thread group.

Thread(ThreadGroup group, Runnable target, String name)

Creates a named thread in a given thread group.

Thread(ThreadGroup group, String name)

Creates a named thread in a given thread group.

Example: Creating a Thread Using Different Constructors

Thread Control Methods

The Thread class provides several methods for controlling execution.

Method

Description

void start()

Starts the thread and calls run() method.

void run()

Defines the task executed by the thread.

static void sleep(long millis)

Makes the current thread sleep for a given time.

void join()

Waits for the thread to finish execution.

void interrupt()

Interrupts a sleeping/waiting thread.

boolean isAlive()

Checks if the thread is still running.

Example

1. start() and run()

  • start(): Creates a new thread and invokes run() on that thread.

  • run(): Executes in the current thread (not a new one).

2. sleep() – Pause Execution

  • sleep(time) pauses the thread for the given milliseconds.

3. join() – Wait for Another Thread to Finish

  • join() makes the calling thread wait until the specified thread finishes execution.

4. interrupt() – Stop a Sleeping/Waiting Thread

  • interrupt() signals a thread to stop execution if it is sleeping or waiting.

5. isAlive() – Check if Thread is Running

  • isAlive() returns true if the thread is still running, else false.

Thread Property Methods

The Thread class provides several methods for thread properties.

Method

Description

setvoid setName(String name)

Sets the thread’s name.

String getName()

Returns the thread’s name.

void setPriority(int priority)

Sets thread priority (1-10).

int getPriority()

Gets thread priority.

static Thread currentThread()

Returns the currently running thread.

void setDaemon(boolean status)

Marks a thread as daemon.

boolean isDaemon()

Checks if the thread is daemon.

Thread State Methods

The Thread class provides several methods for state management.

Method

Description

Thread.State getState()

Returns the thread’s state.

void yield()

Suggests the scheduler to allow other threads to execute.

Thread Interruption Methods

Method

Description

void interrupt()

Interrupts a thread.

boolean isInterrupted()

Checks if a thread is interrupted.

static boolean interrupted()

Checks and clears the interrupt status of the current thread.

Thread Synchronization

When multiple threads access shared resources, synchronization is needed.

Technique

Description

synchronized

Prevents multiple threads from accessing critical sections.

lock

Uses Lock interface (ReentrantLock).

volatile

Ensures visibility of changes to variables across threads.

atomic

Uses classes like AtomicInteger to prevent race conditions.

Example: Synchronized Block

Last updated