Runnable and Thread in Java: How to Create a Thread
There are two ways to create a thread in Java: extend the java.lang.Thread class and override its run() method, or implement the java.lang.Runnable interface and pass the object to a Thread constructor. Either way, you start the thread with start(). Since Java 8 the shortest form is a lambda:
new Thread(() -> System.out.println("Hello from thread " + Thread.currentThread().getName())).start();
// Output: Hello from thread Thread-0 The most common beginner mistake is calling t.run() instead of t.start(). The compiler says nothing, the program runs without exceptions and prints the expected text, except that the line says main instead of Thread-0: no new thread was ever created (see start() vs run()).
Way 1: Extend the Thread Class
The java.lang.Thread class is used to create a new thread. The first way is to declare a subclass, override its run() method (the code the thread will execute) and call start() on the object.
Creating a new thread by extending Thread:
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("Important work running in thread " + getName());
}
} public class MyThreadExample {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
} Important work running in thread Thread-0 Inside the subclass, thread methods are available directly: getName() is called without Thread.currentThread() because this is the thread.
You can overload the run() method, but the Thread object will ignore the overloaded version unless you call it yourself. For example:
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("Important work running in MyThread");
}
public void run(String s) {
System.out.println("String in run: " + s);
}
} Important work running in MyThread After start(), the thread calls only the no-argument run() — that is the Runnable contract. run(String) is just a regular method of the class: call it from main, and it runs in the main thread.
Always add @Override
Make a typo in a Thread subclass and write public void Run(), and the code still compiles. The thread starts and immediately finishes without doing anything: it calls the inherited Thread.run(), which is empty when no Runnable was passed in. With @Override, the same typo is a compile error.
Way 2: Implement the Runnable Interface
Runnable is an interface from the java.lang package with a single method, void run(). It describes a task, not a thread: you pass a Runnable object to a Thread constructor, and after start() the new thread calls its run().
A Java Runnable example that implements java.lang.Runnable:
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Important work running.");
}
} public class MyRunnableExample {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread1 = new Thread(myRunnable);
Thread thread2 = new Thread(myRunnable);
Thread thread3 = new Thread(myRunnable);
thread1.start();
thread2.start();
thread3.start();
}
} Important work running.
Important work running.
Important work running. All three threads execute the same myRunnable object. That's safe as long as the task has no fields. If MyRunnable had, say, a counter, all three threads would modify the same field at the same time, and without synchronization (synchronized, atomic classes) the final value would be unpredictable.
Runnable as a Functional Interface: Lambdas and Method References
Since Java 8, Runnable is annotated with @FunctionalInterface: it has one abstract method, so instead of writing a separate class you can pass the task to Thread as a lambda expression or as a method reference to any method with the shape void name().
public class LambdaThreadExample {
public static void main(String[] args) throws InterruptedException {
Runnable task = () ->
System.out.println("Lambda in thread " + Thread.currentThread().getName());
Thread t1 = new Thread(task, "lambda");
Thread t2 = new Thread(LambdaThreadExample::report, "method-ref");
t1.start();
t1.join(); // wait for t1 so the lines come out in a predictable order
t2.start();
t2.join();
}
private static void report() {
System.out.println("Method reference in thread " + Thread.currentThread().getName());
}
} Lambda in thread lambda
Method reference in thread method-ref Before Java 8 the same thing was written as an anonymous class, new Thread(new Runnable() { public void run() { … } }). You'll still find that style in older projects, and it still works. join() is here only to fix the output order; how it works is covered in Thread.join() in Java.
The void run() signature has a price: the method returns no result and declares no checked exceptions. That's why Thread.sleep() inside a lambda has to be wrapped in try/catch (InterruptedException e) — see InterruptedException: how to handle it.
Thread vs Runnable: Which One to Choose
In most cases prefer Runnable: the task class stays free to extend something else, the task is separated from the mechanism that runs it, and the same object can be handed to a Thread or to a thread pool. Extending Thread only makes sense when you actually change the behavior of the thread itself.
| Criterion | extends Thread | implements Runnable |
|---|---|---|
| Inheritance | Uses up the only superclass: you can't extend another class | The class can extend anything and implement other interfaces |
| Task and thread | Merged into one object | The task is separate from the thread (Thread) |
| One task in several threads | No: one object, one start | Yes: new Thread(task) as many times as you like |
Thread pool (ExecutorService) | Technically accepted (Thread implements Runnable), but the object's own thread is never used — a pool thread runs run() | Accepted directly: execute(task), submit(task) |
| Lambdas and method references | No, you need a class | Yes |
| Access to thread methods | Direct: getName(), isInterrupted() | Through Thread.currentThread() |
| When to choose | Teaching examples, a specialized thread subclass | Almost always |
If the task has to return a result or throw a checked exception, use Callable<V> with its V call() method instead of Runnable. You can't pass it to a Thread constructor, though: it is run through an ExecutorService (or wrapped in a FutureTask, see the FAQ).
start() vs run(): What’s the Difference
start() is a special method that creates a new thread and runs run() in it. run() on its own is an ordinary method: call it directly, and it executes in the current thread like any other method, with no new thread created.
public class StartVsRunExample {
public static void main(String[] args) {
Thread t = new Thread(() ->
System.out.println("run() executes in thread " + Thread.currentThread().getName()));
t.run(); // a plain method call in the main thread
t.start(); // a new thread
}
} run() executes in thread main
run() executes in thread Thread-0 The order of these lines is guaranteed: t.run() finishes completely before main reaches start(). Interviewers like this one as a "what does this code print?" question, and "Thread-0 twice" is the wrong answer.
You can't call start() twice on the same object, even after the thread has finished: the second call throws IllegalThreadStateException. The example with a stack trace and the explanation in terms of thread states are in No way back from TERMINATED: calling start() twice. run(), on the other hand, can be called any number of times — precisely because it doesn't start anything.
Thread Class Constructors
Four Thread constructors cover most cases: no arguments, a Runnable task, a task plus a thread name, and a name only. If no name is passed, the thread gets a name like Thread-N.
Thread()
Thread(Runnable target)
Thread(Runnable target, String name)
Thread(String name) | Constructor | What the thread runs | Thread name | When to use |
|---|---|---|---|
Thread() | The overridden run() of a subclass; without a subclass, nothing | Thread-N | Only in a Thread subclass |
Thread(Runnable target) | target.run() | Thread-N | Quickly starting a task |
Thread(Runnable target, String name) | target.run() | name | The default choice: the name shows up in logs and thread dumps |
Thread(String name) | The overridden run() of a subclass | name | A Thread subclass with a readable name |
Passing target = null doesn't throw: the thread starts and finishes right away. There are also constructors that take a ThreadGroup and a stack size (long stackSize), but application code rarely uses them, and since Java 21 thread parameters are easier to set through a builder — see the last section.
Java Thread Name: setName(), getName() and Thread-N
You set a thread's name in the constructor or with setName() and read it with getName(). If no name is set, the JVM assigns Thread-N, where N is the sequence number of the unnamed thread, starting at 0. Names don't have to be unique: a name is a label for people, not an identifier.
Getting the name of the current thread:
public class NameRunnable implements Runnable {
@Override
public void run() {
System.out.println("NameRunnable running");
System.out.println("Run by "
+ Thread.currentThread().getName());
}
} public class NameThreadExample {
public static void main(String[] args) {
NameRunnable nr = new NameRunnable();
Thread thread1 = new Thread(nr);
thread1.setName("First Thread");
thread1.start();
Thread thread2 = new Thread(nr, "Second Thread");
thread2.start();
}
} NameRunnable running
Run by First Thread
NameRunnable running
Run by Second Thread This is just one possible output. The threads run in parallel, so the Second Thread lines may come first or interleave with the First Thread lines. Java doesn't guarantee the order in which threads execute — more on that in What Java guarantees and what it doesn't.
Both threads run the same nr object, yet print different names: Thread.currentThread() returns the thread that is executing the code right now, not the one in which the task was created. setName() also works after start() — the name changes on the fly. Meaningful names pay off when you read logs and thread dumps: order-worker-3 tells you far more about a problem than Thread-17.
Thread.currentThread() and the Java Main Thread
The static method Thread.currentThread() returns the Thread object of the thread that called it. Inside main that's the main thread, named main, which the JVM creates itself when the program starts.
You control a thread through its Thread object. To get a reference to it, call currentThread(), a public static method of the Thread class. That's what a Runnable task does, and so does any code that doesn't know which thread it will be called from.
public class MainThreadExample {
public static void main(String[] args) {
Thread current = Thread.currentThread();
System.out.println(current.getName());
System.out.println(current);
}
} main
Thread[#1,main,5,main] The second line depends on the Java version. Before Java 19, Thread.toString() printed Thread[main,5,main] — name, priority and group. Java 19 added the thread ID #1 at the front (the same value threadId() returns). If a test or a log parser compares the whole thread string, it breaks when you move to Java 21. All threads of one process, main included, share the same heap, which is why one object can be visible to several threads at once.
Thread.ofPlatform() and Thread.ofVirtual() (Java 21)
Java 21 gave the Thread class a builder: Thread.ofPlatform() creates regular (platform) threads, Thread.ofVirtual() creates virtual threads, and Thread.startVirtualThread(task) starts a virtual thread right away. The task is still a Runnable, and the old constructors keep working.
public class BuilderExample {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
Thread t = Thread.currentThread();
System.out.println("'" + t.getName() + "' virtual: " + t.isVirtual());
};
Thread platform = Thread.ofPlatform().name("worker-", 1).start(task);
platform.join();
Thread virtual = Thread.ofVirtual().name("virtual-1").start(task);
virtual.join();
Thread unnamed = Thread.startVirtualThread(task);
unnamed.join();
}
} 'worker-1' virtual: false
'virtual-1' virtual: true
'' virtual: true Two details in this output. name("worker-", 1) sets a prefix and a starting number, so the next thread from the same builder will be called worker-2. And a virtual thread created without a name gets an empty string, not Thread-N, so in logs such threads are indistinguishable from each other. Instead of start(task) you can call unstarted(task) and start the thread later with a regular start(). How virtual threads look in getState() is covered in Virtual thread states.
Frequently Asked Questions
Can you create a thread with Callable or Future?
Not directly: the Thread constructor accepts only a Runnable, and neither Callable nor Future implements it. So in quiz questions like "which of these can't be used to create a thread", the answer is Callable and Future. In practice a Callable goes to ExecutorService.submit(), which returns a Future with the result. The workaround without a pool is new Thread(new FutureTask<>(callable)).start(): FutureTask implements both Runnable and Future.
What does new Thread(new MyThread()).start() print?
It compiles, because Thread implements Runnable. With MyThread from the first section it prints "Important work running in thread Thread-0", even though the work is done by Thread-1. The argument new MyThread() is created first and gets the name Thread-0; the outer thread becomes Thread-1. Inside run(), getName() refers to the MyThread object, which was never started. Lesson: inside a task, find out the thread via Thread.currentThread().
How do you run the same task in a thread again?
Create a new Thread object with the same Runnable and call start() on it. Restarting the old object isn't possible — you get IllegalThreadStateException (see start() vs run()). If the task runs often, don't create a thread every time; hand the task to an ExecutorService thread pool.
Does the program exit when main finishes but another thread is still running?
No. The JVM waits for all non-daemon threads to finish, and threads created from main are non-daemon by default. To keep a thread from holding the program open, call setDaemon(true) before start(); after the thread has started, that call throws IllegalThreadStateException.
Comments