Java Reference ยท Concurrency
Creating threads in Java
Reference for creating Java threads: Runnable, extending Thread, lambdas, Thread.ofPlatform builders, naming, daemon threads, start versus run and join.
A thread is created by giving a Thread object a task to run and calling start(). The task is usually a Runnable, an interface with one method void run(). The older alternative is to subclass Thread and override run(), but implementing Runnable (or passing a lambda) is almost always preferable because it separates the task from the mechanism that runs it.
start() asks the JVM to create a new thread that will call run(). Calling run() directly does not start anything: it simply executes the method in the current thread, a common beginner mistake.
Thread t = new Thread(() -> System.out.println("hello from " + Thread.currentThread().getName())); t.start(); t.join();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
Thread(Runnable task) Thread(Runnable task, String name) Thread.ofPlatform().name("n").daemon(true).start(Runnable) Thread.ofVirtual().start(Runnable) Thread.startVirtualThread(Runnable)
| Member | Description |
|---|---|
start() |
Schedules the thread. Throws IllegalThreadStateException if already started. |
run() |
The task body. Called by the new thread; calling it yourself runs it in the caller's thread. |
join(), join(long ms) |
Waits for the thread to finish. Throws InterruptedException. |
setName, getName |
Names help in logs and thread dumps. |
setDaemon(boolean) |
Daemon threads do not keep the JVM alive. Must be called before start(). |
setPriority(int) |
A hint (1-10) that most schedulers ignore. |
interrupt(), isInterrupted() |
Cooperative cancellation signal. |
Thread.currentThread() |
The thread executing the call. |
Thread.sleep(long) |
Pauses the current thread; throws InterruptedException. |
setUncaughtExceptionHandler |
Receives exceptions that escape run(). |
Usage notes
RunnableorThread? Implement or pass aRunnable. ExtendingThreaduses up your single superclass and ties the task to a thread type. UseCallablewhen you need a return value or checked exceptions, via an executor.- Output order is not defined when threads run freely. Examples that must be deterministic use
join(). join()creates a happens-before edge: everything the thread wrote is visible to the joining thread afterwards.- A JVM exits when all non-daemon threads finish. Forgetting to stop a pool or a loop thread leaves the program hanging.
- Exceptions in a thread end only that thread; the default handler prints the stack trace to
System.err. - Cost: a platform thread reserves stack memory (about 1 MB by default) and an OS thread; creating thousands is expensive. Use a pool or virtual threads.
- Names: default names look like
Thread-0; the main thread ismain. Virtual threads have an empty name unless you set one. - Do not call
stop(),suspend()orresume(); they are removed or unsafe. Use interruption and flags. - Lambdas capture only effectively final variables; share mutable state through atomics, locks or thread-safe collections.