Sub topic 2
Your First Thread: Thread and Runnable
In the last chapter you learned that a thread is a path of work running inside your program. In this chapter you will make one yourself. You need only two pieces: a Runnable and a Thread.
The two pieces
A Runnable is a Java interface that describes a job to do. It has one method, run(), which holds the code you want to execute. Because it has only one method, you can write a Runnable as a lambda expression.
A Thread is a Java class that represents a real thread of execution. You give it a Runnable, and it runs that job on a new thread.
Keep these roles separate in your mind:
| Piece | What it is | Job |
|---|---|---|
| `Runnable` | An interface | Holds the work to do |
| `Thread` | A class | Runs the work on its own thread |
A worked example
Here is a complete program. It creates a thread named worker-1, 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 HelloThreadYou should see:
Hello from worker-1
Main thread doneLine by line
Runnable task = () -> ...creates the job. The lambda body is therun()method.Thread.currentThread()returns the thread that is running this line right now.getName()returns its name.new Thread(task, "worker-1")builds a thread object. The second argument is a name. Names make output and error messages easier to read.worker.start()tells Java to create the new thread and callrun()on it.worker.join()makes the main thread wait untilworker-1finishes. The next chapter coversjoinin more detail. Here it keeps the two printed lines in a fixed order.
The main thread is the thread Java creates for you to run main. Your program now has two threads: main and worker-1.
The most common mistake: calling run() instead of start()
Calling run() yourself looks like it should work. It does not create a new thread. It runs the job on the current thread, the same way any other method call would.
public class RunVsStart {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> System.out.println("Running on " + Thread.currentThread().getName());
Thread worker = new Thread(task, "worker-1");
worker.run(); // Wrong: runs on main
worker.start(); // Right: runs on worker-1
worker.join();
}
}Output:
Running on main
Running on worker-1Why use Runnable instead of extending Thread?
You can also make a subclass of Thread and override its run() method. Most Java code passes a Runnable instead, for two reasons:
- The job stays separate from the thread that runs it. The same Runnable can run on a plain Thread or, later in this tutorial, on a thread pool.
- Your class can still extend some other class, because a Java class can extend only one class.
Exercises
Exercise
What does the program print if you replace worker.start() with worker.run() in HelloThread, and why?
Show answer
It prints "Hello from main" and then "Main thread done". Calling run() directly runs the lambda on the current thread, which is main, so no new thread is created. join() returns at once because worker-1 was never started.
Exercise
Write a program that starts two threads named "alpha" and "beta". Each one prints its own name, and main waits for both before printing "All done".
Show answer
Create one Runnable, task = () -> System.out.println(Thread.currentThread().getName()). Build new Thread(task, "alpha") and new Thread(task, "beta"), call start() on both, then call join() on both, then print "All done". The alpha and beta lines can appear in either order, because the two threads run at the same time.