×

java · level 3 · unit 5 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A is a second worker inside your program.

Until now, everything ran on one thread, main, one line after another. means several threads making progress at the same time, like two cooks in one kitchen. It makes slow jobs faster, but only if the cooks stay out of each other's way.

new Thread(job) takes a , usually a lambda, and start() sets it running beside main. join() makes main wait until that thread has finished. Waiting can be interrupted, so main must declare throws InterruptedException.

Threads run in an order nobody can predict, so never let them print as they go. Give each thread its own slot to fill, join them all, then report from main. The output is then the same on every run.

public class Main {
    static long sumUpTo(long n) {
        long total = 0;
        for (long i = 1; i <= n; i++) {
            total = total + i;
        }
        return total;
    }
    public static void main(String[] args) throws InterruptedException {
        long[] results = new long[2];
        Thread first = new Thread(() -> results[0] = sumUpTo(1000000));
        Thread second = new Thread(() -> results[1] = sumUpTo(2000000));
        first.start();
        second.start();
        first.join();
        second.join();
        System.out.println("First: " + results[0]);
        System.out.println("Second: " + results[1]);
    }
}

A lambda may fill results[0] because results itself, the reference to the array, never changes.