java · level 3 · unit 5 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
The barista never got going. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
public static void main(String[] args) throws InterruptedException {
int[] cupsMade = new int[1];
Thread barista = new Thread(() -> cupsMade[0] = 12);
barista.join();
System.out.println("Cups made: " + cupsMade[0]);
}
}
your turn
Your turn. Read two chapters at once.
Start both threads on lines 12 and 13, then make main wait for both on lines 14 and 15.
output
press run to see what happens
fix it
The backup report will not compile. Can you fix it?
output
press run to see what happens
- Java says
InterruptedExceptionis not reported. Which line can throw it? joinon line 6 can be interrupted while it waits, and that is a checked exception.- Add
throws InterruptedExceptionaftermain(String[] args)on line 2, then run.
nailed it
you ran two jobs at the same time. :D
start()runs a thread besidemain;join()waits for it.- Give each thread its own slot for its result.
- Print from
mainafter joining, so the output never changes.
new words in your collection
- thread
- concurrency
- Runnable
This lesson isn’t saved. A free account remembers every lesson you finish.