×

java · level 3 · unit 6 · lesson 2

  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 receipt you trade in for the answer.

A Runnable gives nothing back. A does: () -> priceOf(item). Submit one and the pool hands you a Future straight away, like a ticket at a dry cleaner. Later, future.get() trades the ticket for the answer, waiting if the job is still running.

submits a whole list and waits for all of them. Its futures come back in the order of your list, whatever order the threads finished in, so results line up with their jobs every time.

If a job throws, its future keeps the exception. get then throws , with the job's real exception inside as its cause.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Main {
    static int wordsIn(String chapter) {
        return chapter.split(" ").length;
    }
    public static void main(String[] args) throws Exception {
        List<String> chapters = List.of("It begins here", "The storm arrives at last", "Home");
        List<Callable<Integer>> jobs = new ArrayList<>();
        for (String chapter : chapters) {
            jobs.add(() -> wordsIn(chapter));
        }
        ExecutorService pool = Executors.newFixedThreadPool(3);
        List<Future<Integer>> answers = pool.invokeAll(jobs);
        pool.shutdown();
        for (Future<Integer> answer : answers) {
            System.out.println(answer.get());
        }
    }
}

get can throw two checked exceptions, so this main declares throws Exception to cover both.