A thread is an independent path of the execution inside one program. The Java gives you two ways to start one. You create a Thread and you call start, or you hand a task to an executor. Understanding the difference between start and run is the single most important thing in this lesson, because confusing them is the most common threading mistake that the beginners make.
The previous lesson in this module covered "How Do You Read and Write Files With java.nio?", and the next lesson in this module is about "What Causes Race Conditions and How Does synchronized Fix Them?".
How do you start a thread?
There are two constructors that you will use. One of them takes a Runnable, and the other one takes a Runnable and a name. The name matters more than it looks, because it is what appears in the stack traces and the thread dumps, and it is the difference between a readable log line and Thread-3.
public class ThreadBasics {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
System.out.println("running on : " + Thread.currentThread().getName());
System.out.println("is daemon : " + Thread.currentThread().isDaemon());
});
worker.setName("report-worker");
worker.start();
worker.join();
System.out.println("worker finished, alive : " + worker.isAlive());
System.out.println("main thread : " + Thread.currentThread().getName());
}
}The output is this.
running on : report-worker
is daemon : false
worker finished, alive : false
main thread : mainThe order of the output is the thing to notice. The worker starts, it prints its name, and it finishes before main prints the next line. That is not luck. The call join blocks the calling thread until the target thread has finished, so the program is deterministic. Without it, the order of the output would be a race.
What is the difference between start and run?
The call start asks the runtime to create a new thread and to run your task there. The call run just calls the method, on the current thread, immediately, and nothing new is created.
public class StartVersusRun {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
System.out.println("task on : " + Thread.currentThread().getName());
};
Thread thread = new Thread(task, "worker-1");
System.out.println("calling run directly");
thread.run();
System.out.println("calling start");
thread.start();
thread.join();
System.out.println("done");
}
}The output is this.
calling run directly
task on : main
calling start
task on : worker-1
doneLook at the thread names in the output. The line that is printed by the call thread.run() says main, because the task ran on the calling thread. The line that is printed after the start says worker-1, because now there really are two threads. If you write run by mistake, then your program still works. It just quietly loses the concurrency, which is why the bug is so easy to ship.
What do sleep and join actually do?
The call Thread.sleep pauses the current thread for a while and then it lets it continue. It does not release any lock, and it can be interrupted. The call join waits for another thread to finish, and it is the tool that you use to make the concurrent code produce a predictable order.
public class SleepAndJoin {
static void slow(String label, int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println(label + " interrupted");
return;
}
System.out.println(label + " finished");
}
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
Thread a = new Thread(() -> slow("a", 300), "a");
Thread b = new Thread(() -> slow("b", 100), "b");
a.start();
b.start();
b.join();
a.join();
long elapsed = System.currentTimeMillis() - start;
System.out.println("both done after about 300ms, measured " + elapsed + "ms");
}
}The output is this.
b finished
a finished
both done after about 300ms, measured 341msBoth of the tasks sleep, but they sleep at the same time, so the whole program takes about as long as the longer task rather than the sum of the two. That is the entire point of the concurrency, which is the overlapping work. Notice also that the method slow catches the InterruptedException and it restores the interrupt flag with the call Thread.currentThread().interrupt(). Swallowing that exception without restoring the flag is a common and subtle bug.
What are the daemon threads?
A daemon thread does not keep the program alive. When every non-daemon thread has finished, the runtime exits and the daemons are stopped wherever they happen to be. That makes them useful for the background housekeeping that should never hold a process open, such as a monitor that pings a server every few seconds or a cache that expires the entries.
public class DaemonAndState {
public static void main(String[] args) throws InterruptedException {
Thread daemon = new Thread(() -> {
while (true) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
return;
}
}
}, "background");
daemon.setDaemon(true);
System.out.println("state before start : " + daemon.getState());
daemon.start();
Thread.sleep(120);
System.out.println("state while running : " + daemon.getState());
System.out.println("is daemon : " + daemon.isDaemon());
System.out.println("program ends and the daemon stops with it");
}
}The output is this.
state before start : NEW
state while running : TIMED_WAITING
is daemon : true
program ends and the daemon stops with itThe last line of that output is the important one. The program printed its final message and it exited even though the daemon thread was in the middle of its loop, because the main thread, which is a non-daemon thread, had finished. The flip side is that the daemon threads can be killed in the middle of an operation, so you never use one for the work that must complete, such as the flushing of the data to the disk.
What else does a thread tell you?
getState()reports whether the thread is new, runnable, blocked, waiting or terminated.isAlive()says whether the thread has not yet finished.getId()andgetName()identify it in the logs.interrupt()asks a sleeping or waiting thread to stop, which shows up as an InterruptedException.setPriorityandsetDaemonset the hints, and the scheduler is free to ignore the priority entirely.
Should you create the threads directly?
Directly, yes, while you are learning. In the application code, almost always no. You hand the task to an executor instead. A raw Thread per task means one new platform thread per unit of the work, with no limit, no reuse and no clean shutdown. The next-but-one lesson covers the executor, which is the tool that you will actually reach for. Until then, the rule of the thumb is simple. You use a Thread when you want to understand what the concurrency does, and you use an executor when you want to do a job properly.
The habits to keep
- Always call start, and never run, to run a task on another thread.
- Give every thread a name. It pays for itself the first time that you read a stack trace.
- Use join when you need the result, and never assume the order of the println calls.
- Handle the InterruptedException by restoring the interrupt flag.
- Remember that a daemon thread will be cut off when the last non-daemon thread ends.
- Prefer an executor to the raw threads in the application code.
Try it yourself: start three threads that each print their name five times with a short sleep between the prints, then join all three of them and print a final line that says how many finished. Now change one of them to a daemon thread and run the program again. The output should be cut short. Finally, add an interrupt to one thread and show that it responds by leaving the loop early.