Java : Thread with Examples

Thread (Java SE 19 & JDK 19) API Examples.
You will find code examples on most Thread methods.


Summary

A thread is a thread of execution in a program. The Java virtual machine allows an application to have multiple threads of execution running concurrently.

Class diagram

final Runnable task = () -> {
    System.out.println("  Run!");

    final var current = Thread.currentThread();
    System.out.println("  id : " + current.threadId());
    System.out.println("  name : " + current.getName());
    System.out.println("  priority : " + current.getPriority());
};

final var thread = new Thread(task, "name-A");

System.out.println("-- start --");
thread.start();
System.out.println("state : " + thread.getState());

thread.join();
System.out.println("-- join --");
System.out.println("state : " + thread.getState());

// Result
// ↓
//-- start --
//state : RUNNABLE
//  Run!
//  id : 33
//  name : name-A
//  priority : 5
//-- join --
//state : TERMINATED

Fields

static final int MAX_PRIORITY

The maximum priority that a thread can have.

System.out.println(Thread.MAX_PRIORITY); // 10

static final int MIN_PRIORITY

The minimum priority that a thread can have.

System.out.println(Thread.MIN_PRIORITY); // 1

static final int NORM_PRIORITY

The default priority that is assigned to a thread.

System.out.println(Thread.NORM_PRIORITY); // 5

Constructors

Thread ()

Initializes a new platform Thread.

class SampleThread extends Thread {
    @Override
    public void run() {
        System.out.println("Run!");

        System.out.println("name : " + getName());
        System.out.println("priority : " + getPriority());
        System.out.println("group : " + getThreadGroup().getName());
        System.out.println("daemon : " + isDaemon());
    }
}

final var thread = new SampleThread();

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//Run!
//name : Thread-3
//priority : 5
//group : main
//daemon : false
//-- join --

Thread (Runnable task)

Initializes a new platform Thread.

final Runnable task = () -> {
    System.out.println("Run!");

    final var current = Thread.currentThread();
    System.out.println("current : " + current);
};

final var thread = new Thread(task);

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//Run!
//current : Thread[#33,Thread-3,5,main]
//-- join --

Thread (Runnable task, String name)

Initializes a new platform Thread.

final Runnable task = () -> {
    System.out.println("Run!");

    final var current = Thread.currentThread();
    System.out.println("current : " + current);
};

final var thread = new Thread(task, "name-A");

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//Run!
//current : Thread[#33,name-A,5,main]
//-- join --

Thread (String name)

Initializes a new platform Thread.

final var thread = new Thread("name-A") {
    @Override
    public void run() {
        System.out.println("Run!");

        final var current = Thread.currentThread();
        System.out.println("current : " + current);
    }
};

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//Run!
//current : Thread[#33,name-A,5,main]
//-- join --

Thread (ThreadGroup group, Runnable task)

Initializes a new platform Thread.

final var group = new ThreadGroup("group-A");

final Runnable task = () -> {
    System.out.println("Run!");

    final var current = Thread.currentThread();
    System.out.println("current : " + current);
};

final var thread = new Thread(group, task);

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//Run!
//current : Thread[#33,Thread-3,5,group-A]
//-- join --

Thread (ThreadGroup group, Runnable task, String name)

Initializes a new platform Thread so that it has task as its run object, has the specified name as its name, and belongs to the thread group referred to by group.

final var group = new ThreadGroup("group-A");

final Runnable task = () -> {
    System.out.println("Run!");

    final var current = Thread.currentThread();
    System.out.println("current : " + current);
};

final var thread = new Thread(group, task, "name-A");

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//Run!
//current : Thread[#33,name-A,5,group-A]
//-- join --

Thread (ThreadGroup group, Runnable task, String name, long stackSize)

Initializes a new platform Thread so that it has task as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size.

Other than stackSize, please see also Thread(ThreadGroup group, Runnable task, String name).

runTest(1);

// Result
// ↓
//-- start --
//Run!
//StackOverflowError!
//-- join --

runTest(10000000);

// Result
// ↓
//-- start --
//Run!
//OK!
//-- join --
public void runTest(int stackSize) throws InterruptedException {
    final Runnable task = () -> {
        System.out.println("Run!");

        try {
            recursive(0);
            System.out.println("OK!");
        } catch (StackOverflowError e) {
            System.out.println("StackOverflowError!");
        }
    };

    final var thread = new Thread(null, task, "", stackSize);

    System.out.println("-- start --");
    thread.start();

    thread.join();
    System.out.println("-- join --");
}

// A method for StackOverflowError.
public void recursive(int i) {
    if (i > 100000) {
        return;
    }

    recursive(i + 1);
}

Thread (ThreadGroup group, Runnable task, String name, long stackSize, boolean inheritInheritableThreadLocals)

Initializes a new platform Thread so that it has task as its run object, has the specified name as its name, belongs to the thread group referred to by group, has the specified stackSize, and inherits initial values for inheritable thread-local variables if inheritThreadLocals is true.

Other than inheritInheritableThreadLocals, please see also Thread(ThreadGroup group, Runnable task, String name, long stackSize).

runTest(true);

// Result
// ↓
//parent get : abcd
//child get : abcd

runTest(false);

// Result
// ↓
//parent get : abcd
//child get : null
public void runTest(boolean inheritThreadLocals) throws InterruptedException {

    final var threadLocal = new InheritableThreadLocal<String>();

    final Runnable task = () -> {
        threadLocal.set("abcd");

        System.out.println("parent get : " + threadLocal.get());

        final var childThread = new Thread(null, () -> {
            System.out.println("child get : " + threadLocal.get());

        }, "name-A", 0, inheritThreadLocals);

        try {
            childThread.start();
            childThread.join();

        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
        }
    };

    final var parentThread = new Thread(task);

    parentThread.start();
    parentThread.join();
}

Thread (ThreadGroup group, String name)

Initializes a new platform Thread.

final var group = new ThreadGroup("group-A");
final var name = "name-A";

final var thread = new Thread(group, name) {
    @Override
    public void run() {
        System.out.println("Run!");

        final var current = Thread.currentThread();
        System.out.println("current : " + current);
    }
};

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//Run!
//current : Thread[#33,name-A,5,group-A]
//-- join --

Methods

static int activeCount ()

Returns an estimate of the number of live platform threads in the current thread's thread group and its subgroups.

final var groupA = new ThreadGroup("group-A");
final var groupB = new ThreadGroup("group-B");

final var thread = new Thread(groupA, () -> {
    final var current = Thread.currentThread();
    System.out.println(current.getThreadGroup().getName());
    System.out.println("activeCount : " + Thread.activeCount());

    final Runnable task = () -> {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
        }
    };

    try {
        final var t1 = new Thread(task);
        t1.start();
        System.out.println(t1.getThreadGroup().getName());
        System.out.println("activeCount : " + Thread.activeCount());

        final var t2 = new Thread(task);
        t2.start();
        System.out.println(t2.getThreadGroup().getName());
        System.out.println("activeCount : " + Thread.activeCount());

        final var t3 = new Thread(groupB, task);
        t3.start();
        System.out.println(t3.getThreadGroup().getName());
        System.out.println("activeCount : " + Thread.activeCount());

        t1.join();
        t2.join();
        t3.join();

    } catch (InterruptedException e) {
        System.out.println("Interrupted!");
    }
});

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//group-A
//activeCount : 1
//group-A
//activeCount : 2
//group-A
//activeCount : 3
//group-B
//activeCount : 3
//-- join --

final void checkAccess ()

Deprecated, for removal: This API element is subject to removal in a future version. This method is only useful in conjunction with the Security Manager, which is deprecated and subject to removal in a future release.

Deprecated.

protected Object clone ()

Throws CloneNotSupportedException as a Thread can not be meaningfully cloned.

final var thread = new Thread() {
    @Override
    public void run() {
        try {
            System.out.println("Run!");
            clone();
        } catch (CloneNotSupportedException e) {
            System.out.println("CloneNotSupportedException!");
        }
    }
};

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//Run!
//CloneNotSupportedException!
//-- join --

int countStackFrames ()

Deprecated, for removal: This API element is subject to removal in a future version. This method was originally designed to count the number of stack frames but the results were never well-defined and it depended on thread-suspension.

Deprecated.

static Thread currentThread ()

Returns the Thread object for the current thread.

final Runnable task = () -> {
    final var current = Thread.currentThread();
    System.out.println(current.getName());
};

final var threadA = new Thread(task, "name-A");
final var threadB = new Thread(task, "name-B");
final var threadC = new Thread(task, "name-C");

System.out.println("-- start --");
threadA.start();
threadB.start();
threadC.start();

threadA.join();
threadB.join();
threadC.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//name-A
//name-B
//name-C
//-- join --

static void dumpStack ()

Prints a stack trace of the current thread to the standard error stream.

final Thread thread = new Thread(() -> {
    Thread.dumpStack();
});

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//java.lang.Exception: Stack trace
//	at java.base/java.lang.Thread.dumpStack(Thread.java:1380)
//	at ThreadTest.lambda$dumpStack$7(ThreadTest.java:638)
//	at java.base/java.lang.Thread.run(Thread.java:833)
//-- join --

static int enumerate (Thread[] tarray)

Copies into the specified array every live platform thread in the current thread's thread group and its subgroups.

final var groupA = new ThreadGroup("group-A");
final var groupB = new ThreadGroup("group-B");
final var baseThreadName = "name-baseA";

final var baseThread = new Thread(groupA, () -> {
    final Runnable task = () -> {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
        }
    };

    try {
        final var t1 = new Thread(task, "name-A1");
        t1.start();
        final var t2 = new Thread(task, "name-A2");
        t2.start();

        final var t3 = new Thread(groupB, task);
        t3.start();

        final var threads = new Thread[Thread.activeCount()];
        System.out.println("threads length : " + threads.length);

        Thread.enumerate(threads);

        for (final var thread : threads) {
            System.out.println("thread : " + thread.getName());
        }

        t1.join();
        t2.join();
        t3.join();

    } catch (InterruptedException e) {
        System.out.println("Interrupted!");
    }
}, baseThreadName);

System.out.println("-- start --");
baseThread.start();

baseThread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//threads length : 3
//thread : name-baseA
//thread : name-A1
//thread : name-A2
//-- join --

static Map<Thread,StackTraceElement[]> getAllStackTraces ()

Returns a map of stack traces for all live platform threads.

final var thread = new Thread(() -> {

    final var stackTracesMap = Thread.getAllStackTraces();
    for (final var entry : stackTracesMap.entrySet()) {
        System.out.println("============= entry =============");
        final var key = entry.getKey();
        System.out.println("thread name : " + key.getName());

        for (final var stackTraces : entry.getValue()) {
            System.out.println(stackTraces);
        }
    }
}, "name-A");

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//============= entry =============
//thread name : main
//java.base@19.0.2/java.lang.Object.wait0(Native Method)
//java.base@19.0.2/java.lang.Object.wait(Object.java:366)
//java.base@19.0.2/java.lang.Thread.join(Thread.java:2151)
//java.base@19.0.2/java.lang.Thread.join(Thread.java:2227)
//Main.main(Main.java:20)
//...
//============= entry =============
//thread name : name-A
//java.base@19.0.2/java.lang.Thread.dumpThreads(Native Method)
//java.base@19.0.2/java.lang.Thread.getAllStackTraces(Thread.java:2621)
//Main.lambda$main$0(Main.java:5)
//...

ClassLoader getContextClassLoader ()

Returns the context ClassLoader for this thread.

final var thread = new Thread(() -> {
    System.out.println("Run!");
});

final var before = thread.getContextClassLoader();
System.out.println(before); // jdk.internal.loader.ClassLoaders$AppClassLoader@4e25154f

final var url = new URL("file:/R:/java-work/classes");
thread.setContextClassLoader(new URLClassLoader(new URL[]{url}));

final var after = thread.getContextClassLoader();
System.out.println(after); // java.net.URLClassLoader@5c7bfdc1

static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler ()

Returns the default handler invoked when a thread abruptly terminates due to an uncaught exception.

final var handler = new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("uncaughtException called");
        System.out.println("thread name : " + t.getName());
        System.out.println("throwable : " + e.getMessage());
    }
};

System.out.println("handler : " + Thread.getDefaultUncaughtExceptionHandler());

Thread.setDefaultUncaughtExceptionHandler(handler);

System.out.println("handler : " + (Thread.getDefaultUncaughtExceptionHandler() == handler));

final var thread = new Thread(() -> {
    throw new RuntimeException("Exception!");
}, "name-A");

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//handler : null
//handler : true
//-- start --
//uncaughtException called
//thread name : name-A
//throwable : Exception!
//-- join --

long getId ()

Deprecated. This method is not final and may be overridden to return a value that is not the thread ID.

Deprecated. You use threadId() instead.

final String getName ()

Returns this thread's name.

final var thread = new Thread(() -> {
    System.out.println("thread : " + Thread.currentThread().getName());
}, "name-A");

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//thread : name-A
//-- join --
final var thread = new Thread(() -> {
    System.out.println("thread : " + Thread.currentThread().getName());
});

thread.setName("name-B");

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//thread : name-B
//-- join --

final int getPriority ()

Returns this thread's priority.

final var t1 = new Thread(() -> {
    System.out.println("thread default priority : " + Thread.currentThread().getPriority());
});
final var t2 = new Thread(() -> {
    System.out.println("thread min priority : " + Thread.currentThread().getPriority());
});
final var t3 = new Thread(() -> {
    System.out.println("thread max priority : " + Thread.currentThread().getPriority());
});

t2.setPriority(Thread.MIN_PRIORITY);
t3.setPriority(Thread.MAX_PRIORITY);

System.out.println("-- start --");
t1.start();
t2.start();
t3.start();

t1.join();
t2.join();
t3.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//thread default priority : 5
//thread min priority : 1
//thread max priority : 10
//-- join --

StackTraceElement[] getStackTrace ()

Returns an array of stack trace elements representing the stack dump of this thread.

final var thread = new Thread(() -> {
    final var current = Thread.currentThread();
    for (final var stackTrace : current.getStackTrace()) {
        System.out.println(stackTrace);
    }
});

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//java.base/java.lang.Thread.getStackTrace(Thread.java:1610)
//ThreadTest.lambda$getStackTraces$20(ThreadTest.java:1010)
//java.base/java.lang.Thread.run(Thread.java:833)
//-- join --

Thread.State getState ()

Returns the state of this thread.

final var thread = new Thread(() -> {
    final var current = Thread.currentThread();
    System.out.println("state run : " + current.getState());
});

System.out.println("state new : " + thread.getState());

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

System.out.println("state term : " + thread.getState());

// Result
// ↓
//state new : NEW
//-- start --
//state run : RUNNABLE
//-- join --
//state term : TERMINATED

final ThreadGroup getThreadGroup ()

Returns the thread's thread group or null if the thread has terminated.

final var group = new ThreadGroup("group-A");
final var thread = new Thread(group, () -> {
    final var current = Thread.currentThread();
    System.out.println("group : " + current.getThreadGroup());
});

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//group : java.lang.ThreadGroup[name=group-A,maxpri=10]
//-- join --

Thread.UncaughtExceptionHandler getUncaughtExceptionHandler ()

Returns the handler invoked when this thread abruptly terminates due to an uncaught exception.

final var handler = new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("uncaughtException called");
        System.out.println("thread name : " + t.getName());
        System.out.println("throwable : " + e.getMessage());
    }
};

final var thread = new Thread(() -> {
    throw new RuntimeException("Exception!");
}, "name-A");

thread.setUncaughtExceptionHandler(handler);

System.out.println("handler : " + (thread.getUncaughtExceptionHandler() == handler));

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//handler : true
//-- start --
//uncaughtException called
//thread name : name-A
//throwable : Exception!
//-- join --

static boolean holdsLock (Object obj)

Returns true if and only if the current thread holds the monitor lock on the specified object.

final var obj = new Object();
synchronized (obj) {
    System.out.println(Thread.holdsLock(obj)); // true
}

System.out.println(Thread.holdsLock(obj)); // false

void interrupt ()

Interrupts this thread.

final var thread = new Thread(() -> {
    try {
        System.out.println("task start");
        TimeUnit.SECONDS.sleep(1);

    } catch (InterruptedException e) {
        System.out.println("Interrupted!");
    } finally {
        System.out.println("task end");
    }
});

System.out.println("-- start --");
thread.start();

thread.interrupt();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//task start
//Interrupted!
//task end
//-- join --

static boolean interrupted ()

Tests whether the current thread has been interrupted.

final var thread = new Thread(() -> {
    try {
        System.out.println("task start");

        System.out.println("before : " + Thread.interrupted());

        while (!Thread.interrupted()) {
            Thread.onSpinWait();
        }

        System.out.println("after : " + Thread.interrupted());

    } finally {
        System.out.println("task end");
    }
});

System.out.println("-- start --");
thread.start();

Thread.sleep(100);

thread.interrupt();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//task start
//before : false
//after : false
//task end
//-- join --

final boolean isAlive ()

Tests if this thread is alive.

final var thread = new Thread(() -> {
    try {
        System.out.println("task start");
        TimeUnit.SECONDS.sleep(1);

    } catch (InterruptedException e) {
        System.out.println("Interrupted!");
    } finally {
        System.out.println("task end");
    }
});

System.out.println("isAlive : " + thread.isAlive());

System.out.println("-- start --");
thread.start();

System.out.println("isAlive : " + thread.isAlive());

thread.join();
System.out.println("-- join --");

System.out.println("isAlive : " + thread.isAlive());

// Result
// ↓
//isAlive : false
//-- start --
//task start
//isAlive : true
//task end
//-- join --
//isAlive : false

final boolean isDaemon ()

Tests if this thread is a daemon thread.

final var daemonThread = new Thread(() -> {
    try {
        System.out.println("task start");
        TimeUnit.SECONDS.sleep(1);

    } catch (InterruptedException e) {
        System.out.println("Interrupted!");
    } finally {
        System.out.println("task end");
    }
});

daemonThread.setDaemon(true);

System.out.println("-- start --");
daemonThread.start();

TimeUnit.MILLISECONDS.sleep(100);
System.out.println("isDaemon : " + daemonThread.isDaemon());

daemonThread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//task start
//isDaemon : true
//task end
//-- join --

boolean isInterrupted ()

Tests whether this thread has been interrupted.

final var thread = new Thread(() -> {
    try {
        System.out.println("task start");

        System.out.println("before : " + Thread.interrupted());

        final var current = Thread.currentThread();
        while (!current.isInterrupted()) {
            Thread.onSpinWait();
        }

        System.out.println("after : " + Thread.interrupted());

    } finally {
        System.out.println("task end");
    }

});

System.out.println("-- start --");
thread.start();

TimeUnit.MILLISECONDS.sleep(100);

thread.interrupt();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//task start
//before : false
//after : true
//task end
//-- join --

final boolean isVirtual ()

Preview. Returns true if this thread is a virtual thread.

Preview.

final void join ()

Waits for this thread to terminate.

final var thread = new Thread(() -> {
    try {
        System.out.println("task : start");
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
        System.out.println("Interrupted!");
    } finally {
        System.out.println("task : end");
    }
});

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//task : start
//task : end
//-- join --

final void join (long millis)

Waits at most millis milliseconds for this thread to terminate.

final var thread = new Thread(() -> {
    try {
        System.out.println("task : start");
        TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
        System.out.println("Interrupted!");
    } finally {
        System.out.println("task : end");
    }
});

System.out.println("-- start --");
thread.start();

thread.join(2 * 1000);
System.out.println("-- join --");

TimeUnit.SECONDS.sleep(5);
System.out.println("-- sleep --");

// Result
// ↓
//-- start --
//task : start
//-- join --
//task : end
//-- sleep --

final void join (long millis, int nanos)

Waits at most millis milliseconds plus nanos nanoseconds for this thread to terminate.

final var thread = new Thread(() -> {
    try {
        System.out.println("task : start");
        TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
        System.out.println("Interrupted!");
    } finally {
        System.out.println("task : end");
    }
});

System.out.println("-- start --");
thread.start();

thread.join(2 * 1000, 1234);
System.out.println("-- join --");

TimeUnit.SECONDS.sleep(5);
System.out.println("-- sleep --");

// Result
// ↓
//-- start --
//task : start
//-- join --
//task : end
//-- sleep --

final boolean join (Duration duration)

Waits for this thread to terminate for up to the given waiting duration.

final var thread = new Thread(() -> {
    try {
        System.out.println("task : start");
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
        System.out.println("Interrupted!");
    } finally {
        System.out.println("task : end");
    }
});

System.out.println("-- start --");
thread.start();

final var ret1 = thread.join(Duration.ofMillis(500));
System.out.println("join1 : " + ret1);

final var ret2 = thread.join(Duration.ofSeconds(2));
System.out.println("join2 : " + ret2);

TimeUnit.SECONDS.sleep(5);
System.out.println("-- sleep --");


// Result
// ↓
//-- start --
//task : start
//join1 : false
//task : end
//join2 : true
//-- sleep --

static Thread.Builder.OfPlatformPREVIEW ofPlatform ()

Preview. Returns a builder for creating a platform Thread or ThreadFactory that creates platform threads.

Preview.

static Thread.Builder.OfVirtualPREVIEW ofVirtual ()

Preview. Returns a builder for creating a virtual Thread or ThreadFactory that creates virtual threads.

Preview.

static void onSpinWait ()

Indicates that the caller is momentarily unable to progress, until the occurrence of one or more actions on the part of other activities.

Please see interrupted().

final void resume ()

Deprecated, for removal: This API element is subject to removal in a future version. This method exists solely for use with suspend(), which has been deprecated because it is deadlock-prone.

Deprecated.

void run ()

This method is run by the thread when it executes.

final var thread = new Thread() {
    @Override
    public void run() {
        System.out.println("Run!");
    }
};

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//Run!
//-- join --

void setContextClassLoader (ClassLoader cl)

Sets the context ClassLoader for this thread.

Please see getContextClassLoader().

final void setDaemon (boolean on)

Marks this thread as either a daemon or non-daemon thread.

Please see isDaemon().

static void setDefaultUncaughtExceptionHandler (Thread.UncaughtExceptionHandler ueh)

Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread.

Please see getDefaultUncaughtExceptionHandler().

final void setName (String name)

Changes the name of this thread to be equal to the argument name.

Please see getName().

final void setPriority (int newPriority)

Changes the priority of this thread.

Please see getPriority().

void setUncaughtExceptionHandler (Thread.UncaughtExceptionHandler ueh)

Set the handler invoked when this thread abruptly terminates due to an uncaught exception.

Please see getUncaughtExceptionHandler().

static void sleep (long millis)

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.

final var start = System.nanoTime();

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

final var sec = (System.nanoTime() - start) / 1000000000.0;
System.out.println(sec); // 1.0088005

static void sleep (long millis, int nanos)

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers.

final var start = System.nanoTime();

Thread.sleep(1000, 999999);

final var sec = (System.nanoTime() - start) / 1000000000.0;
System.out.println(sec); // 1.0012892

static void sleep (Duration duration)

Causes the currently executing thread to sleep (temporarily cease execution) for the specified duration, subject to the precision and accuracy of system timers and schedulers.

final var start = System.nanoTime();

// 1 second.
Thread.sleep(Duration.ofSeconds(1));

final var sec = (System.nanoTime() - start) / 1000000000.0;
System.out.println(sec); // 1.0088005
final var start = System.nanoTime();

// 500 milliseconds.
Thread.sleep(Duration.ofMillis(500));

final var sec = (System.nanoTime() - start) / 1000000000.0;
System.out.println(sec); // 0.5046906

void start ()

Schedules this thread to begin execution.

final var thread = new Thread(() -> System.out.println("Run!"));

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//Run!
//-- join --

static Thread startVirtualThread (Runnable task)

Preview. Creates a virtual thread to execute a task and schedules it to execute.

Preview.

final void stop ()

Deprecated, for removal: This API element is subject to removal in a future version. This method is inherently unsafe.

Deprecated.

final void suspend ()

Deprecated, for removal: This API element is subject to removal in a future version. This method has been deprecated, as it is inherently deadlock-prone.

Deprecated.

final long threadId ()

Returns the identifier of this Thread.

final var t1 = new Thread(() -> {
    System.out.println("thread 1 : " + Thread.currentThread().threadId());
});
final var t2 = new Thread(() -> {
    System.out.println("thread 2 : " + Thread.currentThread().threadId());
});
final var t3 = new Thread(() -> {
    System.out.println("thread 3 : " + Thread.currentThread().threadId());
});

System.out.println("-- start --");
t1.start();
t2.start();
t3.start();

t1.join();
t2.join();
t3.join();
System.out.println("-- join --");

// Result
// ↓
//-- start --
//thread 1 : 33
//thread 2 : 34
//thread 3 : 35
//-- join --

String toString ()

Returns a string representation of this thread.

final var thread = new Thread(new ThreadGroup("group-A"),
        () -> System.out.println("Run!"), "name-A");

thread.setPriority(7);

final var str = thread.toString();
System.out.println(str);

System.out.println("-- start --");
thread.start();

thread.join();
System.out.println("-- join --");

// Result
// ↓
//Thread[#33,name-A,7,group-A]
//-- start --
//Run!
//-- join --

static void yield ()

A hint to the scheduler that the current thread is willing to yield its current use of a processor.

API spec says "It is rarely appropriate to use this method." Therefore, the code example is omitted.


Related posts

To top of page