Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Thread.start()

Starts a thread: its code begins running in parallel with the caller.

Available since: Java 1.0

Syntax

public void start()

Examples

Two threads each compute their own part:

void main() throws InterruptedException {
    long[] sums = new long[2];
    Thread a = new Thread(() -> { for (int i = 1; i <= 500; i++) sums[0] += i; });
    Thread b = new Thread(() -> { for (int i = 501; i <= 1000; i++) sums[1] += i; });
    a.start();
    b.start();
    a.join();
    b.join();
    IO.println(sums[0] + sums[1]);
}

Output:

500500

Notes

Calling run() instead of start() is a common mistake: the code runs in the current thread with no parallelism. The same Thread object cannot be started twice — IllegalThreadStateException. The order in which threads run is not defined, so wait for them with join() before using their results.

See also

  • Thread — A thread of execution that lets a program do several things at once.
  • Thread.join() — Waits for a thread to finish.
  • Runnable — A task with no arguments and no result.

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.