Card 01/ 08
Java Threads: Running Work Alongside main
Four two-second calls that do not depend on each other can take two seconds instead of eight.
A thread is an independent path of execution through your program. Every Java program starts with one, the thread that runs main, and creating a second means two parts of your program run at the same moment instead of one after the other.
A report has to fetch four things from four services. Each call takes two seconds, none of them needs the others, and the report takes eight seconds, because the code runs one line after another.
Thread worker = new Thread(() -> {
System.out.println("fetching");
fetchRates();
});
worker.start();
System.out.println("main carries on");The lambda passed to new Thread is the work the thread will do. start() is the line that creates the second path: it returns immediately, and from that moment two things happen at once. The new thread runs the lambda, and main carries on to the next line without waiting. Creating the Thread object alone starts nothing: until start() is called, the thread exists and runs no code.
Four threads, one per fetch, turn the eight seconds into about two. The cost is that the order things happen in stops being the order they are written in, which is what every other topic in this subject deals with.
← → move through sections and cards