Java Threads: Creating and Running Threads with Runnable and Thread
Start your first Java threads: what threads are compared with processes, putting a task in a Runnable, starting it with Thread.start, waiting with join, why calling run() is a bug, Java 21 thread builders, and why you shouldn't subclass Thread. Includes a two-thread bank transfer example.
kvi5hnuCode Sprout team member8 min readOn this page
Your operating system runs many programs at once: you can download a file while editing a document. That is multitasking. Each program runs as a process, and the OS hands out CPU time slices so that even a single core seems to do several things at once. On modern multicore machines, several processes really do run at the same moment.
Multithreading takes the same idea one level down. A single program runs several threads (short for threads of control) that execute concurrently. A browser downloads several images at once, a web server handles many requests at the same time, and a GUI keeps responding while a long computation runs in the background.
This article starts Part 10 of the course, which covers Java concurrency from the basics up to virtual threads, locks, concurrent collections and CompletableFuture. We begin with the simplest possible thing: running a task in a new thread.
Processes versus threads
The key difference: each process has its own memory, but the threads of one process share the same heap. All threads in a JVM see the same objects.
- Sharing makes communication cheap. Threads just read and write the same objects, with no pipes or sockets in between.
- Sharing is also what makes concurrency hard. Two threads updating the same object can corrupt it, as article 97 on race conditions shows.
- Threads are lighter than processes. Creating one costs much less than launching a program. Platform threads still aren't free, though, which is why Java 21 added virtual threads (article 94).
Running a task in a separate thread
It takes three steps:
-
Put the task's code in the
runmethod of aRunnable. The interface has a single abstract method, so a lambda works:javapublic interface Runnable { void run(); } Runnable task = () -> { // task code }; -
Construct a
Threadfrom theRunnable:javavar t = new Thread(task); -
Start the thread:
javat.start();
start returns immediately. From then on, the new thread executes task.run() while the calling thread carries on with its next statement. Both run concurrently, interleaved by the scheduler or truly in parallel on different cores.
Example: two threads moving money
Picture a bank with four accounts. One task repeatedly transfers random amounts from account 0 to account 1. Another transfers from account 2 to account 3. Each task sleeps briefly after every transfer:
Runnable task1 = () -> {
try {
for (int i = 0; i < STEPS; i++) {
bank.transfer(0, 1, MAX_AMOUNT * random.nextDouble());
Thread.sleep(Duration.ofMillis(random.nextInt(3)));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
};
new Thread(task1).start();
new Thread(task2).start();
If both tasks printed every transfer, you would see their lines interleaved in an unpredictable order, and different on each run. (Each println call writes its whole line atomically, but output built from several print calls can be mixed mid-line.) That is concurrency in action.
Thread.sleep pauses the current thread. It can throw the checked InterruptedException, which is how another thread asks this one to stop. Article 94 covers interruption properly. For now, the standard response is to restore the interrupt flag and let the task end, as the code above does. Since Java 19, sleep and join also accept a java.time.Duration.

Waiting for a thread: join
t.join() blocks the calling thread until t has finished. The variants join(millis) and join(Duration) give up after a timeout. join is also how results become safely visible: everything a thread wrote before ending is guaranteed to be visible to a thread that returns from join on it. The demo uses that to collect two partial sums. Without join or other synchronization, reading another thread's writes is not guaranteed to work at all (article 99 explains the memory model).
Ways to create threads
Subclassing Thread. You can extend Thread and override run:
class MyThread extends Thread {
public void run() { /* task code */ }
}
new MyThread().start();
This is no longer recommended. It ties what to do (the task) to how it runs (a dedicated platform thread). Keep tasks as Runnables or Callables instead, and you can hand the same task to a plain thread, a virtual thread, a thread pool, or a scheduled executor without changing it.
Thread builders (Java 21). Thread.ofPlatform() and Thread.ofVirtual() return builders that configure and start threads fluently:
Thread t = Thread.ofPlatform().name("worker-", 1).daemon(true).start(task);
Thread v = Thread.ofVirtual().name("request-handler").start(task);
Thread v2 = Thread.startVirtualThread(task); // shortcut
Builders can also create unstarted threads (unstarted(task)) and ThreadFactory objects for executors.
Executors. In real applications you rarely create threads by hand at all. You submit tasks to an executor service, which manages threads for you and returns results through futures. Article 95 covers this, and it is the approach to use in production code.
A complete example
The demo runs the two bank tasks with seeded random generators. Because each task touches its own pair of accounts and uses its own generator, the final balances are the same on every run even though the threads interleave unpredictably. Then it compares run() with start(), uses Java 21 builders for a platform and a virtual thread, shows the Thread subclass style, and splits a sum across two threads.
import java.time.Duration;
import java.util.*;
public class Solution {
static class Bank {
private final double[] accounts;
Bank(int n, double initialBalance) {
accounts = new double[n];
Arrays.fill(accounts, initialBalance);
}
void transfer(int from, int to, double amount) {
if (accounts[from] < amount) return;
accounts[from] -= amount;
accounts[to] += amount;
}
double balance(int i) { return accounts[i]; }
double total() {
double sum = 0;
for (double a : accounts) sum += a;
return sum;
}
}
static final int STEPS = 100;
static final double MAX_AMOUNT = 1000;
// a task that moves random amounts between two accounts, with short pauses
static Runnable transfers(Bank bank, int from, int to, long seed) {
return () -> {
var random = new Random(seed); // one generator per task: no sharing
try {
for (int i = 0; i < STEPS; i++) {
bank.transfer(from, to, MAX_AMOUNT * random.nextDouble());
Thread.sleep(Duration.ofMillis(random.nextInt(3)));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore the flag and let the task end
}
};
}
public static void main(String[] args) throws InterruptedException {
// 1. two threads running at the same time
var bank = new Bank(4, 100_000);
Thread t1 = new Thread(transfers(bank, 0, 1, 1), "mover-0-1");
Thread t2 = new Thread(transfers(bank, 2, 3, 2), "mover-2-3");
t1.start();
t2.start();
System.out.println("main continues while " + t1.getName() + " and " + t2.getName() + " run");
t1.join(); // wait for both to finish
t2.join();
System.out.printf(Locale.US, "balances %.2f %.2f %.2f %.2f, total %.2f%n",
bank.balance(0), bank.balance(1), bank.balance(2), bank.balance(3), bank.total());
System.out.println("after join: " + t1.getName() + " alive? " + t1.isAlive() + ", state " + t2.getState());
// 2. start() versus run()
Runnable whoAmI = () -> System.out.println(" task runs in thread: " + Thread.currentThread().getName());
Thread worker = new Thread(whoAmI, "worker");
System.out.println("worker.run():");
worker.run(); // just a method call in the current thread
System.out.println("worker.start():");
worker.start(); // a new thread executes run()
worker.join();
// 3. Java 21 thread builders
Thread built = Thread.ofPlatform().name("built-", 1).start(whoAmI);
built.join();
Thread virtual = Thread.ofVirtual().name("virtual-1").start(whoAmI);
virtual.join();
System.out.println("isVirtual: " + built.isVirtual() + " / " + virtual.isVirtual());
// 4. subclassing Thread works but couples the task to the mechanism
class Countdown extends Thread {
@Override public void run() {
var sb = new StringBuilder(" countdown in " + getName() + ":");
for (int i = 3; i > 0; i--) sb.append(' ').append(i);
System.out.println(sb);
}
}
Thread c = new Countdown();
c.setName("countdown");
c.start();
c.join();
// 5. results come back through shared state that the joining thread reads
int[] partialSums = new int[2];
Thread low = new Thread(() -> { for (int i = 1; i <= 500; i++) partialSums[0] += i; });
Thread high = new Thread(() -> { for (int i = 501; i <= 1000; i++) partialSums[1] += i; });
low.start(); high.start();
low.join(); high.join(); // join makes the writes visible to main
System.out.println("sum 1..1000 computed by two threads: " + (partialSums[0] + partialSums[1]));
}
}
main continues while mover-0-1 and mover-2-3 run
balances 43641.69 156358.31 50286.27 149713.73, total 400000.00
after join: mover-0-1 alive? false, state TERMINATED
worker.run():
task runs in thread: main
worker.start():
task runs in thread: worker
task runs in thread: built-1
task runs in thread: virtual-1
isVirtual: false / true
countdown in countdown: 3 2 1
sum 1..1000 computed by two threads: 500500
The total stays at 400,000 because the two threads never touch the same account. Once two threads transfer between the same accounts, money starts to vanish, as you'll see in the article on race conditions.
Common questions
What is the difference between start() and run()?
start() creates a new thread, which then calls run(). Calling run() yourself is an ordinary method call in the current thread, and no new thread is created.
Should I extend Thread or implement Runnable?
Implement Runnable (or Callable) and keep the task separate from the thread. The same task can then run on a platform thread, a virtual thread or an executor. Extending Thread is legacy style.
Can I call start() twice on the same thread?
No. The second call throws IllegalThreadStateException, even after the thread has finished. Create a new Thread, or submit the task to an executor again.
Does the JVM exit when main returns while other threads are still running?
No. The JVM keeps running until all non-daemon threads have finished. Daemon threads, including all virtual threads, don't keep it alive.
Do I need join to see the results another thread computed?
You need some form of synchronization. join is one: everything the thread wrote before it ended is visible after join returns. Without it, or another mechanism such as a Future, a lock or a volatile field, you might read stale values.
API reference
java.lang.Thread
| Method | Description |
|---|---|
Thread(Runnable target), Thread(Runnable target, String name) | a new, unstarted thread that will call target.run() |
void start() | starts the thread; returns immediately while run executes concurrently |
void run() | calls the target's run in the current thread; don't call it directly |
static void sleep(long millis), static void sleep(Duration d) (Java 19) | pauses the current thread; throws InterruptedException |
void join(), void join(long millis), boolean join(Duration d) (Java 19) | waits for this thread to terminate, optionally with a timeout; the Duration version returns true if the thread terminated |
static Thread currentThread() | the thread executing the caller |
String getName(), void setName(String) | the thread's name, useful in logs and thread dumps |
static Thread.Builder.OfPlatform ofPlatform(), static Thread.Builder.OfVirtual ofVirtual() (Java 21) | builders for configuring and starting threads |
java.lang.Runnable
| Method | Description |
|---|---|
void run() | the task to run; implement it, usually with a lambda |
Summary
- A thread is an independent flow of control inside a process. Threads share the heap, which makes communication easy and correctness hard.
- To run a task concurrently, put it in a
Runnable, wrap it in aThread, and callstart(). start()returns immediately.join()waits for completion and makes the thread's writes visible.- Calling
run()directly doesn't create a thread. - Prefer passing
Runnabletasks to builders or executors over subclassingThread. Java 21 addsThread.ofPlatform(),Thread.ofVirtual()andstartVirtualThread.
Practice Questions
What is the essential difference between two processes and two threads?
Processes have separate address spaces, so each has its own copy of all variables. Threads within one process share the same heap, so they can access the same objects directly. That makes communication cheap but requires synchronization.
A colleague writes new Thread(task).run() and says "threads work". What actually happens?
run() executes task.run() synchronously in the current thread. No new thread starts, so there is no concurrency. It should be start().
Why is extending Thread discouraged?
It couples the task to one execution mechanism, a dedicated platform thread. A Runnable can be run by a platform thread, a virtual thread, a pool or a scheduler without changes. Extending Thread also uses up your single superclass.
The main thread starts a thread that fills an array, then immediately reads the array. What could go wrong, and how do you fix it?
The main thread may read before the other thread has written anything, and even after the writes happen, without synchronization they aren't guaranteed to be visible to main. Call t.join() before reading. It waits for completion and establishes visibility.
How do you start a named virtual thread in Java 21?
Thread.ofVirtual().name("my-task").start(runnable), or Thread.startVirtualThread(runnable) if you don't need a name.
Previous: Java Legacy Collections: Hashtable, Enumeration, Properties, Stack and BitSet
Next: Java Thread States: New, Runnable, Blocked, Waiting and Terminated
Related reading
- Java Object Construction: Overloading, Default Fields, this(), and Initialization Blocks
- Java Block Scope and if/else Statements
- The Java String API, Code Points, StringBuilder and Text Blocks
- Java Long-Running Tasks in User Interfaces: Swing Worker Threads and Callbacks
- Java CompletableFuture: Asynchronous Programming with Callbacks and Composition

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.