CKTIS / Java
Thread.start(): starting a thread
`Thread.start()` schedules code to run in a separate thread. Calling `run()` directly does not start a thread; use `join()` when you need to wait for it to finish.
Version: Java SE 21
Syntax
public void start()
// Call on a java.lang.Thread instance:
thread.start();Thread.start() is a no-argument instance method of java.lang.Thread that returns no value (void). In Java SE 21, it schedules that platform or virtual thread to execute independently of the caller. It does not wait for the thread to finish or guarantee that its code runs before the caller's next statement. Each Thread object can be started only once. A second call to start() throws IllegalThreadStateException, even if the thread has already terminated.
new Thread(task) creates a platform thread without starting it. Calling run() directly on that object executes the task synchronously in the calling thread; it does not start a new thread. Calling run() directly on a virtual thread does nothing. Use start() to execute the task in a separate thread.
Call join() after start() if later code must wait for the thread to terminate. join() can throw InterruptedException if the waiting thread is interrupted. The happens-before rules make the caller's writes before start() visible to the started thread, and the started thread's writes visible to the waiting thread after join() returns successfully. This does not make arbitrary concurrent updates to shared data safe.
Examples
public class ThreadStartDemo {
public static void main(String[] args) throws InterruptedException {
Thread caller = Thread.currentThread();
Runnable task = () -> System.out.println(
Thread.currentThread() == caller ? "caller thread" : "worker thread");
Thread worker = new Thread(task);
worker.run();
worker.start();
worker.join();
System.out.println("worker finished");
}
}Result
caller thread worker thread worker finished
The same task runs first on the calling thread (`caller thread`), then on the worker (`worker thread`). After `join()`, the program prints `worker finished`.
Related lessons
- Java · Lesson 49 · Intermediate · Version: 2
- Java · Lesson 52 · Intermediate · Version: 2
- Java · Lesson 53 · Intermediate · Version: 2
- Java · Lesson 58 · Intermediate · Version: 2