Java Threads: Thread Basics
A thread is a single path of execution inside a running program. Java threads let one program do several things at the same time: download files while the user keeps typing, check many servers at once, or split heavy work across all CPU cores.
This lesson explains what a thread is, how the main thread works, how two threads run side by side, how threads share memory, and the difference between user, daemon, platform and virtual threads. Every idea comes with a runnable example.
What Is a Thread in Java?
When you start a Java program, the operating system creates a process for the JVM. A process owns memory, open files and other resources. Inside that process, the work is done by one or more threads.
Think of a process as a kitchen and threads as the cooks in it. All cooks share the same kitchen (memory), but each cook follows their own recipe (code path) at their own pace.
| Concept | Process | Thread |
|---|---|---|
| What it is | A running program | A path of execution inside a process |
| Memory | Has its own, separate memory | Shares the heap with other threads of the same process |
| Cost to create | High | Much lower |
| Communication | Needs files, sockets or pipes | Can read and write the same objects directly |
| Example | Two separate java commands | The main thread plus a download thread in one program |
Note: "Multithreading" means a program uses more than one thread. On a machine with several CPU cores, threads can run truly in parallel. On a single core, the operating system switches between them very quickly, so they appear to run at the same time.
The Main Thread in Java
Every Java program already has one thread before you write any threading code: the main thread. The JVM creates it and uses it to call your main method. You can get a reference to the thread that is running the current code with Thread.currentThread().
public class MainThreadDemo {
public static void main(String[] args) {
// Every Java program starts on a thread called "main"
Thread current = Thread.currentThread();
System.out.println("Thread name : " + current.getName());
System.out.println("Thread id : " + current.threadId());
System.out.println("Priority : " + current.getPriority());
System.out.println("Is alive : " + current.isAlive());
System.out.println("Is daemon : " + current.isDaemon());
System.out.println("CPU cores : " + Runtime.getRuntime().availableProcessors());
}
}
Output (the core count depends on your machine):
Thread name : main
Thread id : 1
Priority : 5
Is alive : true
Is daemon : false
CPU cores : 2
How it works:
Thread.currentThread()returns theThreadobject for whichever thread executes that line. Here it is the main thread.- Every thread has a name, a unique id (
threadId(), Java 19+), and a priority from 1 to 10; the default is 5. availableProcessors()tells you how many threads can run truly in parallel on this machine.
Running Two Java Threads at the Same Time
To run code on a new thread, create a Thread object, give it a task, and call start(). The task below is written as a lambda. From that moment on, the new thread and the main thread run concurrently.
public class TwoThreadsDemo {
public static void main(String[] args) throws InterruptedException {
// A second thread with its own job to do
Thread worker = new Thread(() -> {
for (int step = 1; step <= 3; step++) {
System.out.println("worker: step " + step);
pause(100);
}
}, "worker");
worker.start(); // the worker now runs at the same time as main
for (int step = 1; step <= 3; step++) {
System.out.println("main : step " + step);
pause(100);
}
worker.join(); // wait until the worker has finished
System.out.println("Both threads finished");
}
static void pause(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Output from one run (the order of the middle lines changes between runs):
worker: step 1
main : step 1
main : step 2
worker: step 2
main : step 3
worker: step 3
Both threads finished
How it works:
new Thread(task, "worker")only creates the thread. Nothing runs untilstart()is called.- After
start(), both loops run at the same time, so their lines mix together. - The thread scheduler of the operating system decides which thread runs when. You cannot predict the exact order, which is why the output differs from run to run.
join()makes main wait for the worker. Without it, "Both threads finished" could print before the worker is done.
Note: Never rely on the order in which threads print or run. If one step must happen after another, you have to coordinate the threads explicitly, for example with
join().
Why Use Threads? Faster Programs with Concurrency
Threads are most useful when a task spends time waiting: for the network, a disk, a database or a user. While one thread waits, others can keep working.
The example below simulates three downloads of 500 ms each. First it runs them one after another, then on three threads.
public class SpeedDemo {
// Simulates a slow task such as downloading a file (500 ms each)
static void download(String fileName) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Downloaded " + fileName + " on " + Thread.currentThread().getName());
}
public static void main(String[] args) throws InterruptedException {
String[] files = {"report.pdf", "photo.jpg", "data.csv"};
// 1. One after another on the main thread
long start = System.currentTimeMillis();
for (String file : files) {
download(file);
}
long sequentialMs = System.currentTimeMillis() - start;
// 2. One thread per file, all running at the same time
start = System.currentTimeMillis();
Thread[] workers = new Thread[files.length];
for (int i = 0; i < files.length; i++) {
String file = files[i];
workers[i] = new Thread(() -> download(file), "downloader-" + (i + 1));
workers[i].start();
}
for (Thread worker : workers) {
worker.join();
}
long concurrentMs = System.currentTimeMillis() - start;
System.out.println("Sequential: about " + Math.round(sequentialMs / 100.0) * 100 + " ms");
System.out.println("Threads : about " + Math.round(concurrentMs / 100.0) * 100 + " ms");
}
}
Output from one run:
Downloaded report.pdf on main
Downloaded photo.jpg on main
Downloaded data.csv on main
Downloaded photo.jpg on downloader-2
Downloaded report.pdf on downloader-1
Downloaded data.csv on downloader-3
Sequential: about 1500 ms
Threads : about 500 ms
How it works:
- Sequentially, each download waits for the previous one: 3 × 500 ms = about 1500 ms.
- With threads, all three waits overlap, so the whole job takes about as long as the slowest download.
- The three "Downloaded" lines from the threads appear in a random order, because the threads finish at almost the same moment.
Common reasons to use threads:
| Goal | Example |
|---|---|
| Keep an application responsive | A desktop app loads data in the background while the window stays usable |
| Wait for many things at once | A server handles hundreds of client requests at the same time |
| Use all CPU cores | Image processing or number crunching split into chunks (see Java Parallel Streams) |
| Run periodic background jobs | Saving a cache every minute, sending heartbeats |
How Java Threads Share Memory
All threads of a program share the heap, the memory area where objects and static fields live. Each thread also has its own stack, which holds its local variables and method calls. That means:
- Local variables inside a thread's code are private to that thread.
- Objects, arrays and static fields can be seen by every thread that has a reference to them.
public class SharedMemoryDemo {
// Lives on the heap: every thread can see this array
static long[] partialSums = new long[2];
public static void main(String[] args) throws InterruptedException {
Thread first = new Thread(() -> {
long localSum = 0; // local variable: private to this thread's stack
for (int n = 1; n <= 500; n++) {
localSum += n;
}
partialSums[0] = localSum; // write the result to the shared array
});
Thread second = new Thread(() -> {
long localSum = 0;
for (int n = 501; n <= 1000; n++) {
localSum += n;
}
partialSums[1] = localSum;
});
first.start();
second.start();
first.join(); // after join, main is guaranteed to see the thread's writes
second.join();
System.out.println("First half : " + partialSums[0]);
System.out.println("Second half: " + partialSums[1]);
System.out.println("Total 1..1000 = " + (partialSums[0] + partialSums[1]));
}
}
Output:
First half : 125250
Second half: 375250
Total 1..1000 = 500500
How it works:
- Each thread has its own
localSum. The two variables have the same name but live on different stacks, so they never interfere. - Each thread writes to a different slot of the shared array, so they never touch the same data.
join()does two jobs: it waits for the thread to end, and it guarantees that main sees every value the thread wrote before it ended.
The Danger of Shared Data: A First Look at Race Conditions
Problems start when two threads change the same data at the same time. The statement counter++ looks like one step, but the CPU performs three: read the value, add 1, write it back. If two threads do this simultaneously, one update can overwrite the other.
public class RaceDemo {
static int counter = 0; // shared and NOT protected
public static void main(String[] args) throws InterruptedException {
Runnable addOneHundredThousand = () -> {
for (int i = 0; i < 100_000; i++) {
counter++; // read, add 1, write back: three steps
}
};
Thread a = new Thread(addOneHundredThousand);
Thread b = new Thread(addOneHundredThousand);
a.start();
b.start();
a.join();
b.join();
System.out.println("Expected: 200000");
System.out.println("Actual : " + counter);
}
}
Output from one run (the actual number changes every time):
Expected: 200000
Actual : 178255
How it works:
- Both threads read, for example,
counter = 41, both add 1, and both write42. Two increments happened, but the counter only grew by one. - This kind of bug is called a race condition: the result depends on the timing of the threads.
- The fix is to protect shared data, using tools such as
synchronizedblocks or atomic classes, which later lessons in this section cover in detail.
Note: Reading shared data that no thread changes is always safe. Trouble only starts when at least one thread writes data that another thread also uses.
User Threads and Daemon Threads
Java has two kinds of threads with respect to shutting down:
| Type | Keeps the JVM running? | Typical use |
|---|---|---|
| User thread (default) | Yes. The JVM waits for all user threads to finish | Real work: requests, file processing, calculations |
| Daemon thread | No. The JVM stops daemon threads when the last user thread ends | Background helpers: heartbeats, cache cleanup, monitoring |
public class DaemonDemo {
public static void main(String[] args) throws InterruptedException {
Thread heartbeat = new Thread(() -> {
int beat = 1;
while (true) { // never ends on its own
System.out.println("heartbeat " + beat++);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
return;
}
}
});
heartbeat.setDaemon(true); // a background helper thread
heartbeat.start();
Thread.sleep(500); // main does its work for half a second
System.out.println("main finished - JVM exits, daemon thread is stopped");
}
}
Output:
heartbeat 1
heartbeat 2
heartbeat 3
main finished - JVM exits, daemon thread is stopped
How it works:
- The heartbeat loop never ends by itself. As a user thread, it would keep the program running forever.
setDaemon(true)marks it as a daemon, so whenmain(the only user thread) finishes, the JVM exits and the heartbeat stops.setDaemonmust be called beforestart().
Note: A daemon thread is stopped abruptly, without running
finallyblocks. Never give a daemon thread work that must finish cleanly, such as writing a file.
Platform Threads and Virtual Threads
Since Java 21, there are two kinds of threads with respect to how they are implemented:
| Platform thread | Virtual thread (Java 21+) | |
|---|---|---|
| Backed by | One operating-system thread each | Scheduled by the JVM onto a small pool of OS threads |
| Memory cost | About 1 MB of stack reserved per thread | Small and grows only as needed |
| How many | Thousands | Millions |
| Best for | CPU-heavy work, long-running threads | Tasks that mostly wait: HTTP calls, database queries, file I/O |
| Created with | new Thread(...), Thread.ofPlatform() | Thread.ofVirtual(), Thread.startVirtualThread(...) |
import java.util.ArrayList;
import java.util.List;
public class VirtualThreadsDemo {
public static void main(String[] args) throws InterruptedException {
Thread platform = Thread.ofPlatform().name("platform-worker").start(() -> {});
Thread virtual = Thread.ofVirtual().name("virtual-worker").start(() -> {});
platform.join();
virtual.join();
System.out.println(platform.getName() + " isVirtual = " + platform.isVirtual());
System.out.println(virtual.getName() + " isVirtual = " + virtual.isVirtual());
// 10,000 virtual threads, each waiting one second
long start = System.currentTimeMillis();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 10_000; i++) {
threads.add(Thread.startVirtualThread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}));
}
for (Thread thread : threads) {
thread.join();
}
long elapsed = System.currentTimeMillis() - start;
System.out.println("10000 virtual threads finished in about "
+ Math.round(elapsed / 100.0) * 100 + " ms");
}
}
Output from one run on a 2-core machine:
platform-worker isVirtual = false
virtual-worker isVirtual = true
10000 virtual threads finished in about 1100 ms
How it works:
Thread.ofPlatform()andThread.ofVirtual()return a builder;start(task)creates and starts the thread in one step.- 10,000 virtual threads each sleep for one second, yet the whole job takes only a little over one second. While a virtual thread sleeps or waits, the JVM frees its OS thread for others.
- Doing the same with 10,000 platform threads would use far more memory and could fail on smaller machines.
The rest of this section uses platform threads to explain the fundamentals, which apply to both kinds. The Virtual Threads lesson at the end of the section covers them in depth.
Real-World Example: Concurrent Website Health Checker
A monitoring tool checks several websites and reports which ones are up. Each check mostly waits for a response, so checking all sites at the same time is much faster than checking them one by one. The network wait is simulated with sleep so the example runs anywhere.
import java.util.Map;
public class HealthChecker {
// Simulated response times in milliseconds (a real checker would make HTTP calls)
static final Map<String, Integer> LATENCY_MS = Map.of(
"gocourse.in", 300,
"api.gocourse.in", 450,
"cdn.gocourse.in", 200,
"blog.gocourse.in", 900);
static final int TIMEOUT_MS = 800;
record CheckResult(String site, String status, int millis, String checkedBy) { }
static CheckResult check(String site) {
int latency = LATENCY_MS.get(site);
int waited = Math.min(latency, TIMEOUT_MS);
try {
Thread.sleep(waited); // stands in for waiting on the network
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
String status = latency <= TIMEOUT_MS ? "UP" : "TIMEOUT";
return new CheckResult(site, status, waited, Thread.currentThread().getName());
}
public static void main(String[] args) throws InterruptedException {
String[] sites = {"gocourse.in", "api.gocourse.in", "cdn.gocourse.in", "blog.gocourse.in"};
CheckResult[] results = new CheckResult[sites.length]; // one slot per thread
Thread[] checkers = new Thread[sites.length];
long start = System.currentTimeMillis();
for (int i = 0; i < sites.length; i++) {
int slot = i; // effectively final copy for the lambda
checkers[i] = new Thread(() -> results[slot] = check(sites[slot]), "checker-" + (i + 1));
checkers[i].start();
}
for (Thread checker : checkers) {
checker.join(); // wait for every check before reading results
}
long elapsed = System.currentTimeMillis() - start;
int totalWait = 0;
System.out.printf("%-18s %-8s %6s %s%n", "SITE", "STATUS", "TIME", "THREAD");
for (CheckResult r : results) {
System.out.printf("%-18s %-8s %4d ms %s%n", r.site(), r.status(), r.millis(), r.checkedBy());
totalWait += r.millis();
}
System.out.println("Sum of all waits : " + totalWait + " ms");
System.out.println("Actual time taken: about " + Math.round(elapsed / 100.0) * 100 + " ms");
}
}
Output:
SITE STATUS TIME THREAD
gocourse.in UP 300 ms checker-1
api.gocourse.in UP 450 ms checker-2
cdn.gocourse.in UP 200 ms checker-3
blog.gocourse.in TIMEOUT 800 ms checker-4
Sum of all waits : 1750 ms
Actual time taken: about 800 ms
How it works:
- One thread per site. The loop creates a named thread (
checker-1tochecker-4) for each site and starts it immediately, so all four checks run at once. - A lambda needs an effectively final variable. The loop variable
ichanges, so the code copies it intoslotbefore using it inside the lambda. - No shared writes. Each thread stores its
CheckResultin its own slot of theresultsarray, so threads never write the same data and no race condition is possible. - Timeouts. A site that takes longer than 800 ms is reported as
TIMEOUTafter 800 ms, instead of holding up the report. join()before reading. Main waits for all four threads, then safely reads the array and prints the table.- The result: the waits add up to 1750 ms, but because they overlap, the whole report is ready in about 800 ms, the time of the slowest check.
The next lesson, Create a Thread in Java, shows every way to create and start a thread. After that, the Java Thread Class and Java Runnable Interface lessons look at the two building blocks used in these examples in detail.