Threads

A program so far has had one thread, the one the JVM starts for main. A thread is a second sequence of statements that runs at the same time, with its own stack and its own program counter, and the same heap as every other thread. This lesson starts threads, waits for them and reads which thread ran a line.

A thread and a task

The work is a Runnable, which is a functional interface with one method, run. The thread is the machine that runs it, and it takes the task in its constructor with an optional name. The program prints the name of the thread that reaches each line:

public class Start { public static void main(String[] args) throws InterruptedException { Runnable task = () -> System.out.println("running on " + Thread.currentThread().getName()); System.out.println("main is " + Thread.currentThread().getName()); task.run(); System.out.println("after run, same thread"); Thread thread = new Thread(task, "worker"); thread.start(); thread.join(); System.out.println("after join"); Thread second = new Thread(() -> { System.out.println("second on " + Thread.currentThread().getName()); }); second.start(); second.join(); System.out.println("alive: " + second.isAlive()); } }

javac -Xlint:all Start.java
java Start

main is main
running on main
after run, same thread
running on worker
after join
second on Thread-0
alive: false

run against start

The first call is task.run(), and it ran on main: a call of run is an ordinary method call and the thread that made it executes the body. start is the one that makes a new thread: it asks the JVM for one, the thread takes the task and calls run on itself, which is why the fourth line says worker.

That difference is the first mistake in the subject. A program that calls run where it meant start compiles, works, and is sequential: no thread was made, and the output looks right until somebody measures it. A second call of start on the same thread object throws IllegalThreadStateException, because a thread runs once.

join

join waits until the thread has finished, so every line after it sees the work done. Without the join the after join line could print before, after or between the lines of the worker, and the same program would give a different output on every run. The last line asks isAlive after the join, which is false because the thread has ended.

A thread that has finished cannot be started again, and an exception inside a thread does not reach the main thread: it prints its trace on its own and the thread dies. The next lessons show the tools that collect a result and a failure from a thread, because the two plainly do not travel back by themselves.

Three workers

Three threads compute a sum each and write it into their own slot of an array, and the main thread prints the slots after the joins. The order of the output is the order of the array, not the order the threads finished in:

import java.util.ArrayList; import java.util.List; public class Sums { public static void main(String[] args) throws InterruptedException { int[] sums = new int[3]; List<Thread> workers = new ArrayList<>(); for (int i = 0; i < 3; i++) { int part = i + 1; Thread worker = new Thread(() -> { int sum = 0; for (int n = 1; n <= part * 100; n++) { sum += n; } sums[part - 1] = sum; }, "sum-" + part); workers.add(worker); worker.start(); } for (Thread worker : workers) { worker.join(); } int total = 0; for (int i = 0; i < sums.length; i++) { System.out.println("part " + (i + 1) + " sum " + sums[i]); total += sums[i]; } System.out.println("total " + total); System.out.println("threads seen: " + workers.size()); } }

javac -Xlint:all Sums.java
java Sums

part 1 sum 5050
part 2 sum 20100
part 3 sum 45150
total 70300
threads seen: 3

Each thread writes a different element, so the writes do not race and no lock is needed; the joins make the reads safe, because a join is a point where the main thread sees everything the worker did. The sums are the ones of a loop: 1 to 100 is 5050, 1 to 200 is 20100 and 1 to 300 is 45150, and the total is their sum. The part variable is a copy per iteration, because a lambda captures an effectively final value (lesson 082) and would otherwise print the same number three times.

What a thread is

A platform thread is an operating-system thread with a Java wrapper: a stack of its own, a fixed cost of about a megabyte, and a scheduler shared with every other process on the machine. Starting one costs more than a method call, and a program with ten thousand of them spends its memory on stacks. Lesson 122 shows the virtual thread, which is the same API with a Java-side scheduler and a stack that grows.

The three rules that follow from the shared heap are the subject of the rest of the part. A value written by one thread is not guaranteed to be seen by another without a synchronisation point. Two threads that change the same field can lose one of the two changes. And a thread that holds a lock while waiting for another lock can stop the program for ever, which is the deadlock of lesson 119.

Exercises

  1. Call start twice on one thread and print the exception.
  2. Start four threads that each sleep for a different time and join them in the order they were started; print the order they finished in.
  3. Throw an exception inside a thread and show where the trace is printed.
  4. Print Thread.activeCount() before and after starting the workers.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does thread.start() do?

    Answer

    Asks the JVM for a new thread that calls run on the task

    start is the call that makes a thread, and run is the method that thread executes.

  2. What does join do?

    Answer

    Waits until the thread has finished

    The calling thread blocks until the other one ends, which is what makes its writes visible.

  3. Which thread runs the body of a plain task.run() call?

    Answer

    The thread that made the call

    run is an ordinary method, so it executes where it is called and no thread is created.

  4. What does this program print? public class Q1 { public static void main(String[] args) throws InterruptedException { Thread t = new Thread(() -> System.out.println("task"), "w"); System.out.println(t.getName()); t.run(); t.start(); t.join(); System.out.println("done"); } }

    Answer

    w / task / task / done

    The name is w, the run call prints on main, the start prints on the new thread, and join orders the last line.

  5. What happens when start is called twice on one thread?

    Answer

    IllegalThreadStateException, because a thread runs once

    The thread object holds one run, and the second start is refused at run time.

  6. Where does the exception of a thread appear?

    Answer

    On the thread itself, in a trace printed when it dies

    The failure of a thread does not travel back to its starter, which is why futures exist.

  7. Why does a platform thread cost about a megabyte?

    Answer

    Its stack is reserved when it starts

    A platform thread is an operating-system thread with a reserved stack.

  8. What does this program print? public class Q2 { public static void main(String[] args) throws InterruptedException { Thread t = new Thread(() -> System.out.println(Thread.currentThread().getName())); t.start(); t.join(); System.out.println(t.isAlive()); } }

    Answer

    Thread-0 / false

    The task runs on the new thread with the default name, and after join it is finished.

  9. Why is a value written by a worker visible after join?

    Answer

    The join is a synchronisation point between the two threads

    Without a synchronisation point there is no promise that one thread sees another thread write.

  10. What is the task of a thread called?

    Answer

    A Runnable, with the method run

    Runnable is the functional interface for work with no result, and Callable is its result form.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev