Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Thread.currentThread()

Returns the thread that is running the current code.

Available since: Java 1.0

Syntax

public static Thread currentThread()

Return value

ThreadThe Thread object of the current thread.

Examples

The name and kind of the main thread:

void main() {
    Thread t = Thread.currentThread();
    IO.println(t.getName());
    IO.println(t.isVirtual());
}

Output:

main
false

Inside a task the method returns the thread that runs it:

void main() throws InterruptedException {
    Thread worker = new Thread(
        () -> IO.println("Running in " + Thread.currentThread().getName()), "worker-1");
    worker.start();
    worker.join();
 
    Thread virtual = Thread.ofVirtual().start(
        () -> IO.println("Virtual: " + Thread.currentThread().isVirtual()));
    virtual.join();
}

Output:

Running in worker-1
Virtual: true

Notes

Besides logging, the main use is restoring the interrupt flag: if you caught InterruptedException and cannot rethrow it, call Thread.currentThread().interrupt(). The thread number comes from threadId(). Virtual threads have an empty name by default.

See also

  • Thread — A thread of execution that lets a program do several things at once.
  • Thread.ofVirtual() — Creates a virtual thread — a lightweight thread you can start by the million.
  • InterruptedException — A checked exception: a waiting thread was asked to stop.
  • ScopedValue — A value available to code only for the duration of a call — for example, the current user of a request. A replacement for ThreadLocal.

In the tutorial

  • Threads — Threads in Java — the Thread class, starting with start, waiting with join, Thread.sleep, thread names and unpredictable execution order.

Thanks for reading!

Donate to the site — we work hard for you.