JavaScript is disabled. Lockify cannot protect content without JS.

What Is Multithreading in Java? A Step-by-Step Guide!

This article provides a complete guide on What Is Multithreading in Java? It explains how threads work, how to create and run them with practical examples, and how to avoid common thread-safety mistakes.

Imagine you are building a Java application that imports daily sales records from a large CSV file. A store manager clicks Import and then tries to open yesterday’s report. If the same thread handles both the import and the interface, the application may stop responding until the file is processed.

Naturally, you may wonder: Can Java process the file in the background? How do you start another thread? And what happens if two threads try to update the same sales total?

Multithreading in Java allows multiple threads within one program to make progress concurrently. In this example, a worker thread can handle the file import while the UI thread continues responding to clicks and updating the screen.

The benefit depends on the work involved. Reading a file, calling an API, and processing thousands of calculations place different demands on a program. Extra threads can improve responsiveness or throughput, while poorly coordinated threads can cause lost updates, delays, or deadlocks.

What Is Multithreading in Java

In this Oflox® guide, we explain what multithreading is, why it matters, and how to use it with a runnable two-thread example. We also cover the difference between start(), run(), and join(), along with the Java thread lifecycle, thread safety, executors, and virtual threads.

Let’s explore it together!

What Is Multithreading in Java?

Multithreading in Java is the use of two or more threads within one Java program so multiple tasks can make progress concurrently. For example, a program can start two threads to print numbers independently while the main thread waits for them to finish. Java provides Thread to represent a thread and Runnable to describe work a thread can execute.

A thread is a path of execution through a program. When you run a simple Java application, a thread typically called main begins executing the main() method. It follows the method’s instructions in order. If main starts a worker, the worker gains its own path of execution. Both can make progress during the same period.

Each thread has its own call stack, which tracks active method calls and local variables. Threads in the same program can also hold references to the same objects. For instance, two workers can each have a local variable named number and independently count from one to three. If both workers update a field in the same SalesReport object, those updates need coordination.

1. What Is the Difference Between a Process and a Thread?

ConceptMeaningJava example
ProcessA running program with its own address space and operating system resourcesLaunching java SalesApp creates a process that runs the JVM
ThreadA path of execution within a processmain and two report workers run inside the same JVM process
TaskA unit of work that a thread can executeReading a CSV file or calculating the sales total for one branch

This distinction helps when designing an application. One process can contain several threads that share a cache or configuration. Two separate processes generally exchange data through a mechanism such as a network connection, a file, or a message queue. Sharing a Java object between threads is convenient, but mutable shared objects are also where many concurrency bugs begin.

2. Concurrency vs. Parallelism in Java

  • Concurrency means multiple tasks make progress over overlapping periods. A single CPU core can switch between runnable threads. For example, it can give one thread time to run while another is waiting for a file read.
  • Parallelism means work executes at the same time. On a machine with several cores, two threads may perform calculations simultaneously. The JVM, operating system, available CPU capacity, and workload influence what actually happens. Starting two threads creates the opportunity for overlap. It gives neither worker a guaranteed start order nor a guaranteed share of CPU time.

Why Is Multithreading Important in Java?

The value of multithreading depends on the problem you are solving. In a desktop application, a user wants buttons and menus to keep responding during a slow operation. In a back-end service, the team may want to handle more requests without leaving resources idle. In a batch processor, the goal may be to finish a set of calculations sooner by using multiple cores.

Consider a dashboard that retrieves today’s orders and current stock from two independent services. If it waits for the orders response before requesting stock, the two waits add up. When both requests can begin together, their waiting periods can overlap. The dashboard still needs a policy for timeouts and partial failure. For example, it could show the orders and mark the stock figure as temporarily unavailable.

The right first question is what is the program waiting for? If it spends most of its time waiting for network responses, overlapping requests might help. If it spends most of its time computing totals, splitting work may help when there are spare cores. If neither is true, extra threads can add overhead with little benefit.

A Brief History of Multithreading in Java

Java has supported threads, intrinsic locks, and coordination primitives such as wait() and notify() since its early releases. Over time, the platform added libraries that let developers describe tasks, collect results, and reuse execution resources without having to build those mechanisms by hand.

Java milestoneWhat it introducedWhy it matters
Early Java releasesThread, Runnable, and synchronizedPrograms could create threads and coordinate access to shared state
Java 5java.util.concurrent, including the executor frameworkDevelopers could submit work to managed executors and use higher-level concurrency utilities
Java 7ForkJoinPoolA work-stealing pool could handle tasks that split recursively into smaller tasks
Java 8CompletableFutureDevelopers could compose asynchronous operations, combine results, and handle failures
Java 21Virtual threads became a permanent featureApplications could use a thread-per-task style for many workloads that spend substantial time waiting
Java 24Reduced pinning associated with synchronizedBlocking inside synchronised code became less likely to tie up a virtual thread’s underlying platform thread

These additions serve different purposes. A Thread is useful for understanding how execution works. An executor helps manage a stream of work. CompletableFuture helps when operations form a chain or when several asynchronous results need to be combined. Virtual threads change the cost of representing many waiting tasks.

Java Multithreading Example With Two Threads

Create a file called MultithreadingExample.java. The program below creates two named worker threads. Both use the same Runnable, and each prints its own counter from 1 to 3.

public class MultithreadingExample {
    public static void main(String[] args) throws InterruptedException {
        Runnable printNumbers = () -> {
            String name = Thread.currentThread().getName();
            for (int number = 1; number <= 3; number++) {
                System.out.println(name + ": " + number);
            }
        };

        Thread first = new Thread(printNumbers, "Worker-1");
        Thread second = new Thread(printNumbers, "Worker-2");

        first.start();
        second.start();

        first.join();
        second.join();

        System.out.println("All workers finished");
    }
}

With a JDK installed, open a terminal in the directory containing the file and run:

javac MultithreadingExample.java
java MultithreadingExample

On a JDK that supports single-file source execution, such as Java 21, you can also use java MultithreadingExample.java. The output below was observed in one OpenJDK 21 run.

Worker-2: 1
Worker-2: 2
Worker-2: 3
Worker-1: 1
Worker-1: 2
Worker-1: 3
All workers finished

In another run, Worker-1 printed first. A run may also interleave the workers’ lines. Each worker still prints its own numbers in order because its loop is sequential. The main thread prints All workers finished after both join() calls return normally.

1. Define the Work With Runnable

Runnable has one abstract method, run(). The lambda supplies the method body. When either worker executes that body, Thread.currentThread() returns the thread actually executing the code. That is how the same task can print Worker-1 during one execution and Worker-2 during another.

The two workers share the task object, but the loop counter is declared inside the task body. Each execution has its own counter. If you move the counter to a field in a shared object and have both workers increment it, you introduce a different problem: shared mutable state.

2. Create and Start Both Workers

Calling new Thread(printNumbers, “Worker-1”) creates a thread object and assigns its task and name. The worker becomes eligible to execute when you call first.start(). The main thread can continue to second.start() without waiting for the first worker to finish.

The order of the start() calls tells you which start request main makes first. It does not establish which worker prints first. That is the reason the observed output can begin with Worker-2 even though the code calls first.start() first.

3. Wait for Both Workers With join()

When main calls first.join(), it waits if the first worker is still running. The second worker remains free to make progress during that wait. When main reaches second.join(), the second worker might already have finished, in which case the call returns without needing to wait for it.

Try moving first.join() immediately after first.start(). You will have changed the program’s behaviour: the second worker cannot start until the first has finished, because main is still waiting when it would otherwise reach second.start().

Try moving first.join() immediately after first.start(). You will have changed the program’s behaviour: the second worker cannot start until the first has finished, because main is still waiting when it would otherwise reach second.start().

There is a second reason join() matters. After a successful join, Java’s memory model guarantees that actions performed by the finished thread happen-before the joining thread proceeds. That lets main read a worker’s result after joining it. If both workers update the same counter concurrently, their updates still need protection while they run.

How to Create a Thread in Java

1. Implement Runnable

Use Runnable when you want to describe work without tying it to a particular thread class. A lambda is convenient for a short task. A named class can be easier to read when the task has configuration, dependencies, or several methods.

Runnable sendReminder = () ->
    System.out.println("Processing reminder on " + Thread.currentThread().getName());

Thread worker = new Thread(sendReminder, "reminder-worker");
worker.start();

This snippet prints a message. In an application, the task body might read a notification from a queue and send it through a service. By keeping the task separate, you can later submit the same work to an executor.

2. Extend the Thread Class

You can subclass Thread and override run(). This approach makes the link between start() and run() easy to see in a small example.

class ReportThread extends Thread {
    ReportThread() {
        super("report-worker");
    }

    @Override
    public void run() {
        System.out.println("Building report on " + getName());
    }
}

From another method, call new ReportThread().start(). For ordinary application tasks, Runnable keeps the execution policy separate from the business logic and leaves the task class free to extend another class.

3. Submit Tasks to an Executor

An ExecutorService gives you a place to submit work and manage its lifecycle. Use Runnable for a task with no return value or Callable<V> for a task that returns a value. A call to submit() gives you a Future, which can provide the result or expose a failure when you call get.

What Is the Difference Between start(), run(), join(), and sleep()?

MethodWhat it doesPractical detail
thread.start()Schedules the thread to execute independentlyA Thread instance can be started once
thread.run()A direct call to a platform thread’s run() executes its task on the calling thread, when the thread has a task or overrides run()In the main example, replacing second.start() with second.run() prints main for that task
thread.join()Makes the calling thread wait for the target thread to terminateUse it when later work depends on the completion of that thread
Thread.sleep(…)Pauses the current thread for a period, subject to interruption and schedulingThe sleeping thread retains monitors it already holds

If you call run() directly on the second worker in the main example, main performs that task itself. The second thread object is never started. The first worker, which still uses start(), may print at the same time. Looking at Thread.currentThread().getName() makes the distinction visible. Virtual threads should be started through their supported start methods. A direct call to a virtual thread’s run() does nothing.

Java Thread Lifecycle and Key Features

Java exposes six states through Thread.State. These describe what the JVM sees at a given instant. A thread can move between states quickly, so a thread dump is a snapshot of an application in motion.

StateMeaningExample
NEWThe thread has been created and has yet to startImmediately after new Thread(…)
RUNNABLEThe thread is executing or eligible to executeA worker is running its loop or waiting for CPU time
BLOCKEDThe thread is waiting to acquire an intrinsic monitor lockAnother thread holds the lock needed to enter a synchronized block
WAITINGThe thread is waiting for another action with no specified time limitmain calls join() on a worker that is still running
TIMED_WAITINGThe thread is waiting with a time limitIt calls Thread.sleep(500) or a timed form of join()
TERMINATEDThe thread has finished executionA worker returns from run()

Three features matter once you move beyond the first program:

  • Thread names help you connect a log line or thread dump to the work being performed. Use a role-based name such as invoice-export-worker.
  • Interruption gives code a way to request that a thread stop waiting or wind down. Tasks should cooperate by handling an interrupt, propagating it, or restoring the interrupt flag when they cannot rethrow InterruptedException.
  • Synchronisation and visibility let threads coordinate access to shared data. Java offers intrinsic locks, atomic variables, concurrent collections, and completion mechanisms such as join() and Future.get(). Choose one based on what must be coordinated.

Benefits & Challenges of Multithreading in Java

1. Benefits

  • More responsive applications. A billing application can prepare a large export in the background while the user navigates the interface. UI updates should still be made through the UI thread according to the framework’s rules.
  • Overlapping waits. A service can request information from independent systems concurrently and assemble the results when the responses arrive.
  • Potentially faster CPU-bound processing. A media application can resize independent images on multiple cores. The improvement depends on how much work each task performs and what else the machine is doing.
  • Independent task lifecycles. An application can give background jobs their own timeout, cancellation, and reporting policies. A slow report export can then be handled separately from the request that triggered it.

2. Challenges

ChallengeHow it appearsHow to address it
Race conditionStock counts or totals vary depending on when threads update themReduce shared mutable state and protect updates that must happen together
DeadlockTwo threads each wait for a lock the other holdsAcquire locks in a consistent order and keep lock ownership simple
ContentionA queue builds up around the same lock, CPU, or database poolMeasure the bottleneck and reduce concurrent demand on it
Unbounded backlogTasks accumulate faster than workers can process themBound the queue or control admission and decide what happens when capacity is full
Hidden failuresA background task fails and the caller continues unawareObserve task results and define how failures reach the caller or monitoring system

3. Why Can count++ Lose an Update?

Suppose two workers share a counter whose value is 10. Each worker reads 10, adds one, and writes 11. Both workers ran their increment, yet the final value is 11 when you expected 12. The operations overlapped because count++ involves reading the value, calculating the new value, and writing it back.

For a single shared counter, an atomic increment can express the operation directly:

import java.util.concurrent.atomic.AtomicInteger;

// Inside your class:
private final AtomicInteger processed = new AtomicInteger();

public void recordProcessedItem() {
    processed.incrementAndGet();
}

Declaring the original int as volatile can help with visibility, but the three parts of count++ can still overlap. If the business operation involves several values, such as checking available stock and deducting it as one operation, protect the whole sequence. In one JVM, that might mean using the same lock for all relevant access. If several application instances share inventory in a database, enforce the rule at the database layer, such as with a transaction and a conditional update.

Practical Java Multithreading Examples

1. Combine Two Results With ExecutorService

Suppose a retailer has independent order totals for two regions. The example below submits both calculations before waiting for either result. The numbers stand in for two separate calculations or data lookups.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorExample {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        try {
            Future<Integer> north = executor.submit(() -> 120 + 80);
            Future<Integer> south = executor.submit(() -> 90 + 60);
            int totalOrders = north.get() + south.get();
            System.out.println("Total orders: " + totalOrders);
        } finally {
            executor.shutdown();
        }
    }
}

The output is Total orders: 350. These arithmetic operations are deliberately small so the example focuses on submission and result collection. In a real application, give remote calls a time budget and decide what happens if one fails. For an executor that receives a continuous stream of work, also plan the queue capacity. newFixedThreadPool(2) limits the number of active workers and uses an unbounded task queue, so it can accumulate work when submissions consistently outpace processing.

2. Start a Virtual Thread in Java 21 or Later

Virtual threads are Java threads scheduled by the runtime onto platform threads. For many supported blocking operations, a waiting virtual thread can release its underlying platform thread so other work can run. This is useful when an application has many concurrent tasks that spend much of their lifetime waiting for I/O.

public class VirtualThreadExample {
    public static void main(String[] args) throws InterruptedException {
        Thread worker = Thread.ofVirtual().name("order-lookup").start(() ->
            System.out.println("Virtual thread: " + Thread.currentThread().isVirtual())
        );
        worker.join();
    }
}

The output is Virtual thread: true. In a service with many independent blocking tasks, Executors.newVirtualThreadPerTaskExecutor() offers a task-submission API. If those tasks need a database with 20 available connections, they still have to share those connections. Keep downstream limits in place, and measure connection acquisition time as well as request latency.

3. Choose a Design Based on the Workload

WorkloadA reasonable starting pointWhat to check
Import a CSV in a desktop appRun the import in a background task and post progress or completion to the UI threadCan users still interact with the app or cancel the import?
Resize thousands of imagesUse a bounded platform-thread executor and test different levels of concurrencyCPU utilisation, memory usage, throughput, and storage saturation
Call several independent HTTP servicesEvaluate virtual threads for blocking client code on Java 21 or laterRequest deadlines, response times, and limits set by upstream services
Process orders from a queueUse workers with explicit limits for shared servicesQueue age, retry behaviour, and whether duplicate deliveries are safe

5+ Helpful Tools for Java Multithreading

ToolUse it to
jcmdCapture a thread dump and see what Java threads are doing in a running JVM
Java Flight Recorder (JFR)Collect runtime evidence about behaviour over time, including relevant blocking and virtual-thread events
JDK Mission ControlInspect Flight Recorder data and investigate slow periods alongside other JVM activity
Java Microbenchmark Harness (JMH)Compare narrow Java operations with a benchmark harness that supports JVM warm-up and repeated measurements
Application metrics and tracingConnect thread or queue behaviour with request latency, timeouts, and downstream dependencies

For example, if an export service slows down only during the evening rush, first compare the number of pending exports, the time they spend waiting to start, and the duration of each export. If tasks spend most of their time in the queue, investigate capacity or admission. If they start quickly and then stall, use thread dumps, recordings, and dependency metrics to see where they wait. Increasing the worker count before identifying the delay can make a saturated database busier.

Expert Tips and Common Mistakes

1. Keep Shared Data Small

Let each worker produce its own subtotal, then combine the subtotals after the workers finish. This is often easier to reason about than having every worker update the same running total. It can also reduce the time threads spend competing for a lock.

2. Protect the Entire Business Rule

A thread-safe collection protects its individual operations. An application rule can span several operations. For example, “if there is no active job for this customer, create one” needs a single coordination mechanism around the decision and the update. A separate lookup and insert leave room for two workers to make the same decision.

3. Avoid sleep() as a Synchronisation Mechanism

A test that sleeps for 100 milliseconds and then assumes a worker has finished can pass on your laptop and fail on a busy CI runner. Use a Future, a CountDownLatch, or another completion signal that reflects what the worker has actually done. Give the test a timeout so a broken worker cannot leave it hanging indefinitely.

4. Treat Cancellation as Part of the Task

Decide how a task should respond when it can no longer deliver a useful result. An abandoned export might close its input stream and remove a partial file. A request waiting on another service might cancel dependent work when its deadline expires. If your code catches InterruptedException and cannot propagate it, restore the interrupt status with Thread.currentThread().interrupt() so code higher up can react.

5. Measure the Result a User Experiences

If the goal is faster imports, track how long imports take from submission to completion, including queue time. If the goal is a responsive API, watch higher-percentile latency and timeout rates as concurrent traffic grows. Average runtime alone can hide the requests that spend the longest time waiting.

FAQs:)

Q. What is multithreading in Java with a simple example?

A. Multithreading lets one Java program run multiple threads concurrently. For example, create two Thread objects with the same Runnable, call start() on both, and use join() to wait for them to finish. Each thread can print its own numbers, and the order between the two workers can vary.

Q. Can you start the same Java thread twice?

A. No. Starting the same Thread instance a second time throws IllegalThreadStateException, even if that thread already finished. To repeat the task, create a new thread or submit the task to an executor again.

Q. Why does my program print main after I call run()?

A. In the two-worker example, calling a platform thread’s run() directly from main executes its task on the main thread. Thread.currentThread().getName() therefore prints main. Call start() to schedule that work on the named worker thread.

Q. Does join() guarantee that a task succeeded?

A. No. It tells you that the thread has terminated. A worker can terminate after throwing an uncaught exception. When the caller needs a result or needs to distinguish success from failure, an executor with Future.get() provides that information through its result and exception handling.

Q. Does multithreading always make Java faster?

A. No. It can improve throughput when tasks can overlap waiting or use otherwise idle cores. Thread creation, coordination, lock contention, and moving data between tasks can consume the savings. Measure the performance of the whole workload with realistic inputs.

Q. When should I use virtual threads in Java?

A. Consider virtual threads on Java 21 or later when you have many concurrent tasks that spend substantial time waiting for blocking I/O. For long CPU-intensive calculations, available cores still determine how much work can run in parallel.

Conclusion:)

Understanding what multithreading in Java is starts with seeing how one program can run multiple threads. In our two-worker example, Runnable defines the work, start() schedules each worker, and join() lets the main thread wait for both workers to finish.

The two workers may print in a different order each time you run the program. Once they start sharing data, such as a sales total, you also need to protect updates so one worker does not overwrite another’s result.

For Java developers, the practical approach is straightforward. Identify which tasks can run independently, decide how they should finish or report a failure, and measure whether running them concurrently improves performance. An ExecutorService can help manage multiple tasks, while virtual threads are worth evaluating when many tasks spend much of their time waiting for I/O.

At Oflox®, we recommend starting with two workers and one clear goal. Run the example several times, then move first.join() before second.start(). You’ll see how waiting at a different point changes when the second worker can begin.

“Starting a thread is easy. Writing reliable multithreaded code means deciding what each thread owns, what it shares, and when it must wait.” — Mr Rahman, Oflox®

Read also:)

Did Worker-1 or Worker-2 print first when you ran the example? Try running it again and share what changed in the comments below.

Leave a Comment