Sub topic 1
Threads in Java: Running Code Concurrently
Most Java programs you have written so far do one thing at a time. Line one runs, then line two, then line three. This chapter shows how to make a program do several things at once. That is the starting point for everything else in this tutorial. Once several pieces of code run at the same time, they can get in each other's way, and the later chapters show how to stop that from happening.
You should already know basic Java syntax, lambdas, and the Runnable interface.
What a thread is
A thread is a single path of execution through your code. It has its own place in the program (which line it is running now) and its own call stack, which is the list of methods it is currently inside.
Every Java program starts with one thread, called the main thread. It runs your main method. You can create more threads, and each one runs its own code alongside the main thread.
Concurrent execution means two or more threads make progress during the same period of time. On a computer with several processor cores, threads can run at exactly the same moment. On a single core, the computer switches between them very quickly, so they still appear to run together.
Why use more than one thread?
- Speed on multi-core machines. Split a big job into parts and run each part on its own core.
- Responsiveness. A slow task, such as downloading a file, can run in the background while the rest of the program keeps working.
- Handling many clients. A server can give each request its own thread so one slow request does not hold up the others.
Creating and starting a thread
The usual way to create a thread is to give it a Runnable. A Runnable is an interface with one method, run(), which holds the code the thread should execute. Since Runnable has only one method, you can write it as a lambda.
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 + " says " + i);
}
};
Thread t1 = new Thread(task, "worker-1");
Thread t2 = new Thread(task, "worker-2");
t1.start();
t2.start();
System.out.println("main started both workers");
t1.join();
t2.join();
System.out.println("main is done");
}
}Here is what each part does:
new Thread(task, "worker-1")creates a thread object and gives it a name. The thread is not running yet.start()tells the Java runtime to begin a new thread. The new thread callstask.run().Thread.currentThread()returns the thread that is running the current line.getName()gives its name.join()makes the main thread wait until that thread has finished.
Run this program a few times. You might see output like this:
main started both workers
worker-1 says 1
worker-2 says 1
worker-1 says 2
worker-1 says 3
worker-2 says 2
worker-2 says 3
main is doneThe order can change from one run to the next. The lines from each worker stay in order relative to each other, but the two workers mix together unpredictably. Only main is done always comes last, because join() waits for both workers.
The timeline of a multi-threaded program
The diagram below shows how the main thread and the two workers overlap in time.
start() versus run()
Beginners often make this mistake. Calling run() directly does not create a new thread. It runs the code on the thread that called it, like any ordinary method call.
public class StartVsRun {
public static void main(String[] args) throws InterruptedException {
Runnable task = () ->
System.out.println("Running on " + Thread.currentThread().getName());
Thread t = new Thread(task, "worker");
t.run(); // ordinary method call on the main thread
t.start(); // runs the task on a new thread named "worker"
t.join();
}
}Output:
Running on main
Running on workerWaiting for a thread with join()
Without join(), the main thread keeps going straight after start(). If it needs a result from the worker, it may look for that result before the worker has produced it.
public class JoinDemo {
private static String result = "not ready";
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
try {
Thread.sleep(500); // pretend to do slow work
} catch (InterruptedException e) {
return;
}
result = "ready";
});
worker.start();
worker.join(); // remove this line and see what happens
System.out.println(result);
}
}With join(), this prints ready. If you remove the join() line, it almost always prints not ready, because main prints before the worker wakes up from its sleep.
Thread.sleep(ms) pauses the current thread for at least the given number of milliseconds. Both sleep() and join() can throw InterruptedException. An interrupt is a request from another thread asking this one to stop what it is doing. For now, you only need to catch the exception or declare it with throws.
The life of a thread
A thread moves through a set of states. You can check a thread's current state with getState().
| State | Meaning |
|---|---|
| NEW | Created, but `start()` has not been called yet |
| RUNNABLE | Running, or ready to run when the scheduler picks it |
| BLOCKED | Waiting to get a lock (covered in later chapters) |
| WAITING | Waiting with no time limit, for example inside `join()` |
| TIMED_WAITING | Waiting for a set time, for example inside `sleep(500)` |
| TERMINATED | `run()` has finished, either normally or by throwing an exception |
Edge cases worth knowing
- The program keeps running after main ends. The JVM (Java Virtual Machine, the program that runs your Java code) waits for all ordinary threads to finish before it exits. A thread marked with
setDaemon(true)before it starts is a daemon thread. Daemon threads do not keep the JVM alive. - An exception in one thread does not stop the others. If a worker throws an uncaught exception, that worker ends and prints a stack trace. The main thread keeps running.
- Thread names help debugging. Give threads clear names. Error messages and debugging tools show them.
- More threads is not always faster. Each thread uses memory, and switching between threads takes time. Hundreds of busy threads on a four-core machine can run slower than four.
Key methods at a glance
| Method | What it does |
|---|---|
| `new Thread(runnable, name)` | Creates a thread in the NEW state |
| `start()` | Begins running the task on a new thread |
| `run()` | Runs the task on the current thread (no new thread) |
| `join()` | Waits until the thread finishes |
| `Thread.sleep(ms)` | Pauses the current thread |
| `Thread.currentThread()` | Returns the thread running this line |
| `getState()` | Returns the thread's current state |
| `setDaemon(true)` | Marks the thread as a daemon before it starts |
Exercise
In HelloThreads, the two t.start() calls are replaced with t1.run() and t2.run(). What changes in the output, and why?
Show answer
All lines now print in a fixed order: worker-1's three lines, then worker-2's three lines, then "main started both workers", then "main is done". Each line also shows the name "main", because run() is an ordinary method call on the main thread. No new threads are created, so nothing runs concurrently.
Exercise
Write a program that starts three threads named A, B, and C. Each thread prints its name five times. The main thread must print "all done" only after all three have finished.
Show answer
Create one Runnable that loops five times and prints Thread.currentThread().getName(). Create three Thread objects with names "A", "B", and "C" and call start() on each. Then call join() on each of them, and print "all done" after the last join() returns. Declare main with "throws InterruptedException". The lines from A, B, and C may mix in any order, but "all done" is always last.
Exercise
A thread has finished its run() method. What does getState() return, and what happens if you call start() on it again?
Show answer
getState() returns TERMINATED. Calling start() again throws IllegalThreadStateException, because a Thread object can be started only once.