C

Core Java tutorial for beginners

Clean • Professional

Thread Methods in Java – Lifecycle, State, Synchronization & Exceptions

7 minute

Thread Methods

Java provides several useful methods in the Thread class to control and manage threads.

These methods can be categorized for clarity.

learn code with durgesh images

1. Lifecycle Management Methods

These methods control the lifecycle of a thread—from starting, pausing, waiting, interrupting, and checking its status.

learn code with durgesh images

start()

Begins execution of a new thread.

  • Creates a new call stack for the thread.
  • Moves thread from NEW → RUNNABLE → RUNNING.
  • Internally calls the thread’s run() method.
  • Must be called only once per thread.

Example:

Thread t = new Thread(() -> System.out.println("Thread running..."));
t.start();

run()

Contains the actual code that the thread executes.

  • Overridden when extending Thread or implementing Runnable.
  • Runs in a new thread only when invoked through start().
  • Calling run() directly → acts as a normal method call in the current thread.

Example:

public void run() {
    System.out.println("Running task...");
}

join()

Makes the current thread wait until another thread finishes execution.

  • Useful for controlling execution order.
  • Overloaded versions allow timeout:
    • join(long millis)
    • join(long millis, int nanos)

Example:

t.join();       // wait until t completes
t.join(2000);   // wait max 2 seconds

sleep(long millis)

Pauses the currently executing thread for a specific duration.

  • Thread enters TIMED_WAITING state.
  • Does not release any locks.
  • Throws InterruptedException.

Example:

Thread.sleep(1000); // sleep for 1 second

interrupt()

Sends an interrupt signal to a thread.

  • If the thread is in sleep(), wait(), join() → throws InterruptedException.
  • If actively running → sets its interrupt flag.

Used for graceful termination.

Example:

t.interrupt();

isAlive()

Checks whether a thread is still executing.

  • true → thread is running or waiting.
  • false → thread has finished.

Example:

if (t.isAlive()) {
    System.out.println("Thread is still working.");
}

interrupted() (static)

Checks whether the current thread has been interrupted.

  • Returns true if interrupted.
  • Clears the interrupt flag.

Useful in long-running loops.

Example:

if (Thread.interrupted()) {
    System.out.println("Current thread interrupted");
}

isInterrupted()

Checks whether a specific thread has been interrupted.

  • Does not clear the interrupt flag.

Example:

if (t.isInterrupted()) {
    System.out.println("Thread was interrupted");
}

2. Information and State Methods

These methods help you inspect, identify, and monitor threads during execution.

learn code with durgesh images

currentThread()

  • Returns a reference to the currently executing thread.
  • Static method in the Thread class.
  • Useful for debugging, logging, and thread identification.

Example:

Thread t = Thread.currentThread();
System.out.println("Current thread: " + t.getName());

getId()

  • Returns the unique ID assigned to a thread.
  • ID is long and cannot be changed.
  • Useful for debugging and logging.

Example:

Thread t = new Thread(() -> {
    System.out.println("Thread Name: " + Thread.currentThread().getName());
    System.out.println("Thread ID: " + Thread.currentThread().getId());
});
t.setName("Worker-1");
t.start();

getName() / setName(String name)

  • Retrieves or assigns a readable name to the thread.
  • Helps identify threads in logs.

Example:

Thread t = new Thread();
t.setName("Worker-Thread");
System.out.println(t.getName());

getPriority() / setPriority(int)

  • Gets or sets a thread’s priority (1–10).
  • Default priority = NORM_PRIORITY (5).
  • Higher priority may influence CPU scheduling.

Example:

Thread t = new Thread();
t.setPriority(Thread.MAX_PRIORITY);
System.out.println(t.getPriority());

getState()

  • Returns the current state of the thread.
  • From Thread.State enum:
    • NEW
    • RUNNABLE
    • BLOCKED
    • WAITING
    • TIMED_WAITING
    • TERMINATED

Example:

Thread t = new Thread();
System.out.println(t.getState()); // NEW
t.start();
System.out.println(t.getState()); // RUNNABLE

isDaemon() / setDaemon(boolean on)

  • Daemon threads run in background.
  • Must set daemon before starting the thread.

Example:

Thread t = new Thread(() -> System.out.println("Daemon running"));
t.setDaemon(true);
System.out.println(t.isDaemon());

3. Synchronization and Coordination Methods

These methods help threads coordinate, manage locks, and control shared resources safely.

learn code with durgesh images

yield()

  • A static method that hints to the scheduler that the current thread is willing to pause.
  • The thread moves from RUNNING → RUNNABLE state.
  • The scheduler may or may not choose another thread — not guaranteed.
  • Useful when you want to give other threads a chance to execute.

Example:

Thread.yield(); // Suggest scheduler to switch thread

holdsLock(Object obj)

  • A static method that checks if the current thread holds the monitor lock on the given object.
  • Helpful for debugging synchronization problems.
  • Returns:
    • true → current thread owns the lock
    • false → current thread does not own the lock

Example:

Object lock = new Object();

synchronized (lock) {
    System.out.println(Thread.holdsLock(lock)); // true
}

wait(), notify(), notifyAll()

(Belong to Object class, not Thread — but used with synchronized code)

wait()

  • Causes the thread to release the lock and enter the WAITING state.
  • Thread waits until:
    • Another thread calls notify() or notifyAll()
    • Or the thread is interrupted

notify()

  • Wakes one single waiting thread (chosen by JVM).

notifyAll()

  • Wakes all waiting threads on the same object.
  • Commonly used in producer-consumer and other coordination patterns.
  • Must be called inside a synchronized block.

Example:

Object lock = new Object();

Thread t = new Thread(() -> {
    synchronized (lock) {
        try {
            System.out.println("Waiting...");
            lock.wait();
            System.out.println("Notified!");
        } catch (InterruptedException e) { }
    }
});

t.start();

Thread.sleep(1000);

synchronized (lock) {
    lock.notify(); // Wake one waiting thread
}

4. Exception Handling Methods

These methods help you handle uncaught exceptions thrown inside threads.

Useful for logging, error tracking, and gracefully recovering from thread failures.

learn code with durgesh images

getUncaughtExceptionHandler()

  • Returns the handler that will be notified if the thread terminates due to an uncaught exception.
  • If no handler is set, the thread uses the default handler.

Example:

Thread.UncaughtExceptionHandler handler = t.getUncaughtExceptionHandler();
System.out.println(handler);

setUncaughtExceptionHandler(UncaughtExceptionHandler handler)

  • Sets a custom exception handler for the specific thread.
  • Useful for logging or cleaning up resources when unexpected errors occur.

Example:

Thread t = new Thread(() -> {
    throw new RuntimeException("Something went wrong");
});

t.setUncaughtExceptionHandler((th, ex) -> {
    System.out.println("Error in thread: " + th.getName());
    System.out.println("Exception: " + ex.getMessage());
});

t.start();

setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler) (static method)

  • Sets a global handler for all threads that do not have an individual handler.
  • Useful in large applications to create centralized logging.

Example:

Thread.setDefaultUncaughtExceptionHandler((th, ex) -> {
    System.out.println("Default handler caught: " + ex.getMessage());
});

getDefaultUncaughtExceptionHandler() (static method)

Returns the global default handler, if any.

Example:

System.out.println(Thread.getDefaultUncaughtExceptionHandler());

5. Deprecated Methods (Not Recommended)

These methods are part of the Thread class but are deprecated because they are unsafe, can cause deadlocks, data corruption, or inconsistent thread states.

They should never be used in modern Java applications.

stop() — Deprecated, Unsafe

  • Attempts to forcefully terminate a thread.
  • Can leave shared resources in an inconsistent / corrupted state.
  • May interrupt critical sections and break synchronization.

Why unsafe?

Because it stops a thread immediately without giving it a chance to release locks or clean up.

Example (for understanding only — DO NOT USE):

Thread t = new Thread(() -> {
    while (true) {
        System.out.println("Running...");
    }
});

// Deprecated – NOT recommended
// t.stop();

suspend() — Deprecated, Unsafe

  • Temporarily pauses a thread.
  • But it does not release locks, so it may block other threads forever → leads to deadlocks.

Example (for learning only):

Thread t = new Thread(() -> {
    synchronized (this) {
        System.out.println("Working...");
    }
});

// t.suspend();  // Deprecated – may cause deadlock

resume() — Deprecated, Unsafe

  • Used to resume a suspended thread.
  • When combined with suspend(), it becomes highly error-prone.
// t.resume();  // Deprecated – unsafe combo with suspend()

destroy() — Deprecated, Never Implemented

  • Was planned to forcibly destroy a thread.
  • Never implemented in JVM.
  • Calling it throws UnsupportedOperationException.
// t.destroy();  // Deprecated and unsupported

run() vs start()

Featurerun()start()
PurposeContains the code that defines the thread’s taskCreates a new thread and calls run() internally
Thread CreationDoes not create a new threadCreates a new thread of execution
Execution ContextExecutes in the current thread (caller thread)Executes in a new thread managed by JVM
Thread SchedulerNot involved; runs sequentially in the current threadThread scheduler decides when the new thread runs
ConcurrencyNo concurrency; code runs like a normal methodEnables concurrent execution with other threads
Common UseRarely called directly; mainly overridden in a thread classAlways called to start a new thread

Example:

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

public class Main {
    public static void main(String[] args) {
        MyThread t = new MyThread();

        t.run();   // Executes in main thread, not a new thread
        t.start(); // Creates a new thread and runs concurrently
    }
}


Article 0 of 0