Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Thread.currentThread(): accessing the current thread and handling interrupts

Get the Thread object for the code that is running now, and learn how to restore its interrupt status after catching InterruptedException.

Version: Java SE 21

Syntax

public static Thread currentThread()

Thread.currentThread() is a no-argument static method on java.lang.Thread. It returns a reference to the existing Thread object for the thread making the call. It does not create or start a thread. A call in main returns the thread running main; a call in a worker thread returns that worker.

In Java SE 21, when the code runs in a virtual thread, the method returns that virtual thread's object, not the platform thread currently carrying it.

interrupt() is an instance method: it signals an interrupt request to the thread represented by the object you call it on. A thread can always interrupt itself; interrupting a different thread may throw SecurityException. An interrupt does not forcibly stop a thread. When Thread.sleep(...) throws InterruptedException, it clears the current thread's interrupt status. If you catch the exception and cannot propagate it, restore the status with Thread.currentThread().interrupt() so the calling code can detect the interrupt.

isInterrupted() reads the specified thread's interrupt status without changing it. The static Thread.interrupted() method reads and clears the current thread's interrupt status.

Examples

public class Main {
    public static void main(String[] args) {
        Thread current = Thread.currentThread();
        current.interrupt();

        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            System.out.println("In catch: " + current.isInterrupted());
            Thread.currentThread().interrupt();
            System.out.println("After restoring: " + current.isInterrupted());
        }
    }
}

Result

In catch: false
After restoring: true

The thread running `main` sets its own interrupt status before calling `sleep`. The status has been cleared when the `catch` block reads it (`false`), and the next read returns `true` after restoration. No second thread is needed.

Related lessons

  • Java · Lesson 49 · Intermediate · Version: 2
  • Java · Lesson 58 · Intermediate · Version: 2

Sources