Sub topic 1
Threads in Java: Running Code Concurrently
Most programs you write at first do one thing at a time. Java can also do several things at once, using threads. This chapter shows what a thread is, how to start one, and how to wait for it to finish.
What Is a Thread?
A thread is a single path of execution through your program. It runs one statement after another.
Every Java program starts with one thread, called the main thread. It runs your main method.
You can create more threads. When two or more threads run during the same period of time, they run concurrently. On a computer with several processor cores, they may truly run at the same moment. On one core, the system switches between them very quickly.
Why Use Threads?
Threads let a program keep busy while one task is slow. Here are some examples:
- A web server handles many users at once.
- An app downloads a file and keeps its screen responsive.
- A program splits a big calculation across several cores.
Creating and Starting a Thread
A Runnable is an object that holds the code a thread should run. You can write it as a lambda. You pass the Runnable to a Thread, then call start().
The join() method makes one thread wait until another thread finishes.
public class HelloThreads {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
String name = Thread.currentThread().getName();
for (int i = 1; i <= 3; i++) {
System.out.println(name + " step " + i);
}
};
Thread a = new Thread(task, "worker-A");
Thread b = new Thread(task, "worker-B");
a.start();
b.start();
a.join();
b.join();
System.out.println("main: both workers finished");
}
}Run this program a few times. The lines from worker-A and worker-B may mix together in a different order on each run. Here is one possible output:
worker-A step 1
worker-B step 1
worker-B step 2
worker-A step 2
worker-A step 3
worker-B step 3
main: both workers finishedThe last line always comes last, because main waits on join() for both workers.
How the Threads Run
Key Ideas
| Term | Meaning |
|---|---|
| Thread | One path of execution through a program |
| Runnable | An object holding the code a thread runs |
| `start()` | Begins running the thread's code on a new thread |
| `join()` | Waits until that thread has finished |
The order in which threads run is not fixed. The system decides when each one runs. This is harmless when threads only print. In the next chapters you will see the problems that come up when threads share data.
Exercise
In HelloThreads, you replace a.start() and b.start() with a.run() and b.run(). What changes in the output, and why?
Show answer
All lines from worker-A print first, then all lines from worker-B, in the same order on every run. Calling run() executes the task on the main thread, so no new threads are created and nothing runs concurrently. The printed name is also "main" instead of "worker-A" or "worker-B", because Thread.currentThread() is now the main thread.
Exercise
What could happen to the final line if you removed both join() calls?
Show answer
"main: both workers finished" might print before some worker lines. Without join(), the main thread does not wait, so it can reach its last println while the workers are still running.