Sub topic 2
Your First Thread: Thread and Runnable
In the last chapter you learned that a thread is a single path of work inside a program. Every Java program already has one thread, called the main thread. It runs your main method. This chapter shows you how to add more threads yourself.
You will learn the two building blocks Java gives you for this: the Runnable interface and the Thread class. You will also see the most common beginner mistake, which is calling run() instead of start(), and why it matters.
The Two Pieces: Work and Worker
It helps to split a thread into two ideas:
- The work is the code you want to run. In Java, you describe it with a
Runnable. - The worker is the thread that runs that code. In Java, this is a
Threadobject.
A Runnable is an interface. An interface is a list of methods that a class promises to provide. Runnable has exactly one method:
public interface Runnable {
void run();
}The run method takes no arguments and returns nothing. Whatever you put inside it is the job the thread will do.
A Thread is a class from java.lang, so you never need to import it. A Thread object holds a Runnable and knows how to ask the operating system for a real thread to run it.
| Piece | What it is | Its job |
|---|---|---|
| `Runnable` | An interface with one method, `run()` | Describes the work |
| `Thread` | A class in `java.lang` | Runs the work on its own path |
| `start()` | A method on `Thread` | Asks Java to begin a new thread |
| `join()` | A method on `Thread` | Makes the caller wait until the thread finishes |
A Complete First Example
Here is a full program. It creates one extra thread, gives it a name, starts it, and waits for it to finish.
public class HelloThread {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> System.out.println("Hello from " + Thread.currentThread().getName());
Thread worker = new Thread(task, "worker-1");
worker.start();
worker.join();
System.out.println("Main thread done");
}
}Save it as HelloThread.java, then compile and run it:
javac HelloThread.java
java HelloThreadThe output is:
Hello from worker-1
Main thread doneLet's walk through it line by line.
Runnable task = () -> ...creates the work. The arrow->makes a lambda, a short way to write a method without a name. BecauseRunnablehas only one method, Java knows this lambda is the body ofrun().Thread.currentThread()returns the thread that is running this line right now.getName()returns that thread's name. Inside the lambda, this will be the new thread, not the main thread.new Thread(task, "worker-1")creates the worker. The first argument is the work. The second is a name. Names make output and error messages much easier to read.worker.start()begins the new thread. From this point on, two threads are running at the same time: the main thread andworker-1.worker.join()makes the main thread stop and wait untilworker-1is done. You will studyjoinin detail in the next chapter. For now, know that it keepsmainfrom racing ahead.- The last line prints only after the worker has finished, because of
join.
The throws InterruptedException on main is there because join() can throw that checked exception. The next chapter explains what it means.
Three Ways to Give a Thread Its Work
The lambda is the shortest way, but it is not the only one. You will see all three styles in real code, so it is worth knowing each.
Style 1: A lambda
This is what you saw above. It is short and is the usual choice in modern Java.
Thread t = new Thread(() -> System.out.println("Lambda work"));Style 2: A class that implements Runnable
Sometimes the work needs its own fields or is long enough to deserve a name. Then you write a class.
public class PrintTask implements Runnable {
private final String message;
public PrintTask(String message) {
this.message = message;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ": " + message);
}
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new PrintTask("printing from a class"), "printer");
t.start();
t.join();
}
}The PrintTask stores a message in a field. Each PrintTask object can carry different data, which a plain lambda can only do by capturing variables from around it.
Style 3: A subclass of Thread
You can also extend Thread and override its run method.
public class CountThread extends Thread {
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println(getName() + " counts " + i);
}
}
public static void main(String[] args) throws InterruptedException {
CountThread t = new CountThread();
t.setName("counter");
t.start();
t.join();
}
}This works, but most Java developers avoid it. Here is why.
The Big Mistake: run() Instead of start()
Both start() and run() exist on a Thread, and they look similar. They do very different things.
start()creates a new thread, and that new thread callsrun().run()called directly is just a normal method call. It runs on the current thread. No new thread is made.
This program shows the difference:
public class StartVsRun {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> System.out.println("Running on " + Thread.currentThread().getName());
Thread first = new Thread(task, "worker-A");
first.run();
Thread second = new Thread(task, "worker-B");
second.start();
second.join();
}
}The output is:
Running on main
Running on worker-BThe first line says main, not worker-A. Calling run() directly never created a thread. The code compiled and ran with no error, which is what makes this bug easy to miss. Your program just quietly does everything on one thread.
A Thread Can Only Start Once
A Thread object is single-use. After you call start() once, calling it again throws an IllegalThreadStateException. This is true even after the thread has finished.
public class StartTwice {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> System.out.println("work"));
t.start();
t.join();
try {
t.start();
} catch (IllegalThreadStateException e) {
System.out.println("Cannot start a thread twice: " + e);
}
}
}If you want to run the same work again, create a new Thread with the same Runnable. The Runnable can be reused as often as you like. The Thread cannot.
The Order of Output Is Not Guaranteed
When two threads run at once, Java does not promise which one prints first. A part of the operating system called the scheduler decides which thread runs at each moment, and it can switch between them at any time.
Try this program and run it several times:
public class TwoWorkers {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 1; i <= 3; i++) {
System.out.println(Thread.currentThread().getName() + " step " + i);
}
};
Thread a = new Thread(task, "A");
Thread b = new Thread(task, "B");
a.start();
b.start();
a.join();
b.join();
System.out.println("Both done");
}
}One run might print all of A first, then all of B. Another run might mix them, such as A step 1, B step 1, A step 2. Each thread always does its own steps in order: A step 2 never comes before A step 1. But how the two threads mix together can change on every run. The only line you can count on is Both done at the end, because both join calls come before it.
This is a key idea for the rest of the tutorial. Code that depends on one exact mixing order between threads is fragile. Later chapters show what goes wrong when threads share data, and how to protect it.
Useful Thread Details
A few more methods are handy from day one:
| Method | What it does |
|---|---|
| `new Thread(runnable, name)` | Creates a thread with work and a name |
| `setName(String)` / `getName()` | Sets or reads the thread's name |
| `Thread.currentThread()` | Returns the thread running the current line |
| `isAlive()` | Returns `true` if the thread has started and not yet finished |
| `setDaemon(true)` | Marks the thread as a **daemon**, a background thread that does not keep the program running |
A daemon thread is worth one more sentence. Normally, Java keeps running until every non-daemon thread is done. If you mark a thread as a daemon before you start it, Java can exit even while that thread is still working. Daemon threads suit background helpers, such as one that cleans a cache. They are a poor fit for work that must finish.
Summary
- A
Runnabledescribes the work. AThreadruns it on its own path. - Use a lambda or a class that implements
Runnable. ExtendingThreadworks, but it ties the work to the worker. - Call
start()to begin a new thread. Callingrun()directly runs the code on the current thread. - A
Threadcan be started only once. ARunnablecan be reused. - When threads run at the same time, the order of their output is not fixed.
Exercise
A student writes Thread t = new Thread(() -> System.out.println(Thread.currentThread().getName()), "helper"); t.run(); and expects it to print "helper". What does it print, and how should the code be fixed?
Show answer
It prints "main", because calling run() directly is an ordinary method call on the current thread and no new thread is created. Replace t.run() with t.start() (and optionally t.join() to wait for it). Then the lambda runs on the new thread and prints "helper".
Exercise
Write a program that creates three threads named "red", "green", and "blue" from one shared Runnable. Each thread prints its own name. The main thread prints "All colors done" only after all three have finished.
Show answer
public class Colors { public static void main(String[] args) throws InterruptedException { Runnable task = () -> System.out.println(Thread.currentThread().getName()); Thread r = new Thread(task, "red"); Thread g = new Thread(task, "green"); Thread b = new Thread(task, "blue"); r.start(); g.start(); b.start(); r.join(); g.join(); b.join(); System.out.println("All colors done"); } } The three color names may print in any order, but "All colors done" always prints last because of the three join calls.
Exercise
You have a Thread object that has already finished its work. You want to run the same job again. Why does calling start() a second time fail, and what should you do instead?
Show answer
A Thread object can be started only once. Calling start() again throws IllegalThreadStateException, even after the thread has finished. Create a new Thread and pass it the same Runnable, then start the new thread.