Java Threads: Thread Basics

Su Suriya Ravichandran Updated 18 Nov 2026
14 min read ·Lesson 181 of 306

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.

ConceptProcessThread
What it isA running programA path of execution inside a process
MemoryHas its own, separate memoryShares the heap with other threads of the same process
Cost to createHighMuch lower
CommunicationNeeds files, sockets or pipesCan read and write the same objects directly
ExampleTwo separate java commandsThe 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 the Thread object 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 until start() 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:

GoalExample
Keep an application responsiveA desktop app loads data in the background while the window stays usable
Wait for many things at onceA server handles hundreds of client requests at the same time
Use all CPU coresImage processing or number crunching split into chunks (see Java Parallel Streams)
Run periodic background jobsSaving 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 write 42. 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 synchronized blocks 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:

TypeKeeps the JVM running?Typical use
User thread (default)Yes. The JVM waits for all user threads to finishReal work: requests, file processing, calculations
Daemon threadNo. The JVM stops daemon threads when the last user thread endsBackground 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 when main (the only user thread) finishes, the JVM exits and the heartbeat stops.
  • setDaemon must be called before start().

Note: A daemon thread is stopped abruptly, without running finally blocks. 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 threadVirtual thread (Java 21+)
Backed byOne operating-system thread eachScheduled by the JVM onto a small pool of OS threads
Memory costAbout 1 MB of stack reserved per threadSmall and grows only as needed
How manyThousandsMillions
Best forCPU-heavy work, long-running threadsTasks that mostly wait: HTTP calls, database queries, file I/O
Created withnew 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() and Thread.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:

  1. One thread per site. The loop creates a named thread (checker-1 to checker-4) for each site and starts it immediately, so all four checks run at once.
  2. A lambda needs an effectively final variable. The loop variable i changes, so the code copies it into slot before using it inside the lambda.
  3. No shared writes. Each thread stores its CheckResult in its own slot of the results array, so threads never write the same data and no race condition is possible.
  4. Timeouts. A site that takes longer than 800 ms is reported as TIMEOUT after 800 ms, instead of holding up the report.
  5. join() before reading. Main waits for all four threads, then safely reads the array and prints the table.
  6. 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Threads: Thread Basics and get answers drawn from it.

Signed-in readers only.