What Is Multithreading and Concurrency in Java?

Learn What Is Multithreading and Concurrency in Java? with practical examples, explanations, best practices, and real-world coding techniques.

Modern Java applications often need to perform multiple tasks without waiting for one operation to finish before starting another. A backend server may process several requests concurrently, a file-processing application may work on multiple files, and a service may perform background tasks while continuing to respond to users.

Java multithreading is the ability to execute multiple threads within a process, while concurrency is the broader concept of managing multiple tasks that can make progress during overlapping periods of time. Understanding both concepts is important for building responsive and reliable Java applications.

Multithreading vs Concurrency

A thread is an execution path managed by the runtime. Concurrency is about dealing with multiple tasks that overlap in execution. Multiple tasks may be executed by multiple threads, but concurrency is a design problem as much as it is a threading problem.

What Is a Thread in Java?

A thread is an independent path of execution within a running Java application. A process can contain multiple threads, and those threads share the process's memory and other resources.

This shared environment makes communication between threads possible, but it also creates the need for careful coordination when multiple threads access the same mutable data.

Process and Thread

Process Thread
Represents a running program. Represents an execution path within a process.
Has its own process-level resources. Shares process resources with other threads.
More isolated from other processes. Can communicate through shared memory.

Why Use Multithreading?

Multithreading can help applications handle independent work efficiently and improve responsiveness. The exact benefit depends on the workload, hardware, blocking behavior, and the concurrency model being used.

Responsive Applications

Background work can be separated from operations that need to respond quickly to a user or client.

Concurrent Request Processing

Server applications can process multiple independent requests concurrently.

Background Work

Logging, scheduled processing, file work, and other tasks can execute independently.

Better Resource Utilization

Appropriate concurrency can allow applications to keep useful work in progress while other operations are waiting.

Important: adding more threads does not automatically make a program faster. Too many threads can increase scheduling overhead, memory usage, contention, and application complexity.

Creating a Thread in Java

Java supports several ways to define concurrent work. Two classic approaches are extending the Thread class and implementing Runnable.

Extending Thread

class WorkerThread extends Thread {

    @Override
    public void run() {

        for (int i = 1; i <= 5; i++) {
            System.out.println(
                Thread.currentThread().getName()
                    + " - "
                    + i
            );
        }
    }
}

public class ThreadExample {

    public static void main(String[] args) {

        Thread first =
            new WorkerThread();

        Thread second =
            new WorkerThread();

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

Calling start() asks Java to begin a new thread of execution. Calling run() directly is simply a normal method call and does not create a new thread.

Implementing Runnable

class DownloadTask implements Runnable {

    @Override
    public void run() {

        System.out.println(
            "Downloading on: "
                + Thread.currentThread().getName()
        );
    }
}

public class RunnableExample {

    public static void main(String[] args) {

        Runnable task =
            new DownloadTask();

        Thread thread =
            new Thread(task);

        thread.start();
    }
}

Runnable separates the task from the thread that executes it. This is generally a more flexible design because the task is not forced to inherit from Thread.

Thread Lifecycle and Thread States

Java exposes thread states through Thread.State. Understanding these states makes it easier to reason about what a thread is doing.

NEW
  |
  | start()
  v
RUNNABLE
  |
  +------> BLOCKED
  |
  +------> WAITING
  |
  +------> TIMED_WAITING
  |
  v
TERMINATED
State Meaning
NEW Thread has been created but has not started.
RUNNABLE Thread is eligible to run or is running under the runtime's scheduling model.
BLOCKED Waiting to acquire a monitor lock.
WAITING Waiting indefinitely for another thread or event.
TIMED_WAITING Waiting for a limited amount of time.
TERMINATED Thread has completed execution.

Race Conditions

One of the most important problems in concurrent programming is a race condition. It happens when the result of an operation depends on the timing or interleaving of multiple threads accessing shared state.

Consider a counter that starts at zero. Two threads each increment it one thousand times. An increment is not necessarily one indivisible operation; it involves reading the current value, calculating a new value, and writing that value back.

Thread A                 Thread B

read count = 10
                         read count = 10

calculate 11
                         calculate 11

write 11
                         write 11

Expected: 12
Actual:   11

The problem is not the increment expression itself. The problem is that multiple threads are operating on shared mutable state without appropriate coordination.

Synchronization in Java

Java provides the synchronized keyword for coordinating access to critical sections guarded by an object's monitor.

class Counter {

    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

Here, synchronized prevents multiple threads from executing the synchronized method on the same Counter instance at the same time.

Testing the Counter

public class CounterDemo {

    public static void main(String[] args)
        throws InterruptedException {

        Counter counter =
            new Counter();

        Thread first =
            new Thread(() -> {
                for (int i = 0; i < 1000; i++) {
                    counter.increment();
                }
            });

        Thread second =
            new Thread(() -> {
                for (int i = 0; i < 1000; i++) {
                    counter.increment();
                }
            });

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

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

        System.out.println(
            "Final count: "
                + counter.getCount()
        );
    }
}

join() allows the current thread to wait until another thread terminates. In this example, the main thread waits for both worker threads before reading the final count.

synchronized Blocks

Synchronizing an entire method can be broader than necessary. A synchronized block allows a smaller critical section to be protected.

public void increment() {

    synchronized (this) {
        count++;
    }
}

Smaller critical sections can reduce contention, but synchronization should still be designed around a clear ownership model rather than added randomly whenever concurrency appears difficult.

ExecutorService and Thread Pools

Creating a new Thread for every task is often a poor design for server-style workloads. Java provides the ExecutorService API for managing task execution through executor implementations and thread pools.

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

public class ExecutorExample {

    public static void main(String[] args) {

        ExecutorService executor =
            Executors.newFixedThreadPool(3);

        for (int i = 1; i <= 5; i++) {

            final int taskId = i;

            executor.submit(() -> {

                System.out.println(
                    "Task "
                        + taskId
                        + " executed by "
                        + Thread.currentThread().getName()
                );
            });
        }

        executor.shutdown();
    }
}

A thread pool allows the application to reuse a controlled number of worker threads instead of creating an unlimited number of threads.

Callable and Future

Runnable is useful for tasks that do not return a result. When a task needs to produce a value or report an exception, Callable and Future provide a useful abstraction.

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

public class FutureExample {

    public static void main(String[] args)
        throws Exception {

        ExecutorService executor =
            Executors.newFixedThreadPool(2);

        Callable<Integer> task = () -> {

            Thread.sleep(1000);

            return 42;
        };

        Future<Integer> future =
            executor.submit(task);

        System.out.println(
            "Doing other work..."
        );

        Integer result =
            future.get();

        System.out.println(
            "Result: " + result
        );

        executor.shutdown();
    }
}

Calling get() waits when necessary for the computation to complete. Therefore, Future does not magically make the caller non-blocking; the caller still needs to decide when and how the result should be consumed.

Locks and Explicit Synchronization

The java.util.concurrent.locks package provides explicit locking mechanisms such as ReentrantLock.

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class SafeCounter {

    private final Lock lock =
        new ReentrantLock();

    private int count;

    public void increment() {

        lock.lock();

        try {
            count++;
        } finally {
            lock.unlock();
        }
    }

    public int getCount() {
        return count;
    }
}

With explicit locks, the application is responsible for releasing the lock. Using a finally block is important so that an exception does not accidentally leave the lock held.

Atomic Variables

For simple shared counters and related state, atomic classes can provide thread-safe operations without manually protecting every operation with a synchronized block.

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicCounter {

    private final AtomicInteger count =
        new AtomicInteger();

    public void increment() {
        count.incrementAndGet();
    }

    public int getCount() {
        return count.get();
    }
}

Atomic classes are useful for specific atomic state transitions, but they are not a replacement for every synchronization problem.

Concurrent Collections

Standard collections are not automatically safe for arbitrary concurrent modification. Java provides specialized concurrent collections for applications that need thread-safe access patterns.

import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentMapExample {

    public static void main(String[] args) {

        ConcurrentHashMap<String, Integer> counts =
            new ConcurrentHashMap<>();

        counts.merge(
            "Java",
            1,
            Integer::sum
        );

        counts.merge(
            "Java",
            1,
            Integer::sum
        );

        System.out.println(
            counts
        );
    }
}

Other concurrency utilities include structures and coordination mechanisms designed for different workloads. The correct choice depends on the operations the application needs rather than simply choosing the most advanced-looking API.

volatile and Visibility

Concurrency is not only about protecting operations from overlapping. Threads also need to observe shared state correctly. The volatile keyword can provide visibility guarantees for a shared variable, but it does not make compound operations such as count++ atomic.

class Worker {

    private volatile boolean running = true;

    public void stop() {
        running = false;
    }

    public void work() {

        while (running) {
            // Continue work
        }
    }
}

volatile is useful for specific visibility requirements, but synchronization, atomic variables, locks, or higher-level concurrency utilities may be required when multiple operations must behave as one coordinated action.

CompletableFuture for Asynchronous Workflows

Java also provides CompletableFuture for composing asynchronous computations.

import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {

    public static void main(String[] args) {

        CompletableFuture<String> future =
            CompletableFuture
                .supplyAsync(
                    () -> "Java"
                )
                .thenApply(
                    value -> value + " Concurrency"
                );

        System.out.println(
            future.join()
        );
    }
}

CompletableFuture becomes particularly useful when several asynchronous operations need to be composed rather than managed as a sequence of manually created threads.

Virtual Threads

Modern Java also supports virtual threads, which are lightweight threads designed to support large numbers of concurrent tasks, particularly workloads that spend significant time waiting on blocking operations.

public class VirtualThreadExample {

    public static void main(String[] args)
        throws InterruptedException {

        Thread thread =
            Thread.startVirtualThread(() -> {

                System.out.println(
                    "Running on a virtual thread"
                );
            });

        thread.join();
    }
}

Virtual threads do not eliminate the need for concurrency design. Applications still need to consider shared mutable state, synchronization, blocking behavior, resource limits, and correct coordination between tasks.

Multithreading and Shared Resources

The most difficult concurrency problems usually appear when multiple threads interact with the same mutable resource.

User Request A ----                                         > Shared Booking Data
                    /
User Request B ----/

       Risk:
       Both requests modify the same state
       at nearly the same time.

This is common in systems such as ticket booking, inventory management, counters, account balances, task queues, and reservation systems. The application must define which state is shared and what operations need atomicity or coordination.

Interrupting Threads

Java provides interruption as a cooperative mechanism for communicating that a thread should stop what it is doing or respond to cancellation.

Thread worker = new Thread(() -> {

    try {

        while (!Thread.currentThread().isInterrupted()) {

            System.out.println(
                "Processing..."
            );

            Thread.sleep(500);
        }

    } catch (InterruptedException ex) {

        Thread.currentThread().interrupt();

        System.out.println(
            "Worker interrupted."
        );
    }
});

worker.start();

Thread.sleep(1500);

worker.interrupt();

Interruption should normally be handled cooperatively. A thread that catches InterruptedException should not blindly swallow the signal when its surrounding application expects cancellation to propagate.

Common Multithreading Problems

Race Conditions

Multiple threads modify shared state without sufficient coordination, causing incorrect results.

Deadlocks

Two or more threads can wait indefinitely for resources held by one another.

Thread Contention

Excessive synchronization can cause threads to spend too much time waiting for shared resources.

Too Many Threads

Creating unlimited threads can increase memory usage and scheduling overhead without improving throughput.

Ignoring Exceptions

Exceptions occurring during background tasks need deliberate handling instead of being silently discarded.

Best Practices for Java Concurrency

Minimize Shared Mutable State

The less mutable data threads share, the fewer synchronization problems you need to solve.

Prefer Higher-Level APIs

ExecutorService, concurrent collections, atomic classes, and CompletableFuture can provide better abstractions than manually managing every Thread.

Keep Critical Sections Small

Protect only the state that actually requires coordination.

Design for Cancellation

Long-running work should have a sensible way to stop or respond to interruption where appropriate.

Test Concurrent Behavior

Concurrency bugs can be timing-dependent, so tests should deliberately exercise shared-state scenarios.

Do Not Assume More Threads Means More Speed

Measure the workload and understand whether it is CPU-bound, I/O-bound, or limited by another resource.

Choosing the Right Concurrency Tool

Requirement Useful Tool
Simple independent task Runnable
Task returning a result Callable + Future
Controlled task execution ExecutorService
Simple shared counter AtomicInteger or synchronization
Thread-safe key-value access ConcurrentHashMap
Explicit lock control Lock / ReentrantLock
Composable asynchronous operations CompletableFuture
Large numbers of lightweight concurrent tasks Virtual threads

Practical Example: Thread-Safe Seat Booking

A booking system is a useful example because two users can attempt to reserve the same limited resource at nearly the same time.

class SeatBookingService {

    private int availableSeats = 1;

    public synchronized boolean bookSeat(
        String passenger
    ) {

        if (availableSeats <= 0) {

            System.out.println(
                passenger
                    + ": Seat unavailable"
            );

            return false;
        }

        availableSeats--;

        System.out.println(
            passenger
                + ": Booking successful"
        );

        return true;
    }
}

public class BookingDemo {

    public static void main(String[] args)
        throws InterruptedException {

        SeatBookingService service =
            new SeatBookingService();

        Thread first =
            new Thread(() ->
                service.bookSeat("Passenger A")
            );

        Thread second =
            new Thread(() ->
                service.bookSeat("Passenger B")
            );

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

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

The synchronized method ensures that the check and update of the available-seat state are performed under the same monitor lock for this service instance. Only one booking attempt can execute that critical section at a time.

Key Takeaways

  • A Java thread is an execution path inside a running process.
  • Concurrency is broader than simply creating multiple Thread objects.
  • Calling start() creates a new thread of execution; calling run() directly does not.
  • Java thread states include NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED.
  • Race conditions occur when concurrent access to shared state is not correctly coordinated.
  • synchronized can protect critical sections involving shared mutable state.
  • ExecutorService provides a higher-level model for managing task execution.
  • Callable and Future are useful when concurrent tasks need to return results.
  • Atomic classes are useful for certain thread-safe state transitions.
  • Concurrent collections provide specialized data structures for concurrent access.
  • CompletableFuture supports composable asynchronous workflows.
  • Virtual threads provide a lightweight concurrency model for suitable workloads.
  • More threads do not automatically mean better performance.
  • Good concurrent design minimizes shared mutable state and makes synchronization intentional.

Summary

Java multithreading allows multiple execution paths to make progress within an application, while Java concurrency provides a wider set of tools and design techniques for coordinating those tasks. This becomes especially important in backend systems, background processing, network applications, and other software that handles many operations concurrently.

Starting with Thread and Runnable helps explain the basic model, but production applications often benefit from higher-level tools such as ExecutorService, Callable, Future, atomic classes, concurrent collections, locks, CompletableFuture, and virtual threads.

The most important lesson is that concurrency is primarily about correctness and coordination. Shared mutable state, race conditions, visibility, cancellation, resource limits, and synchronization all need to be considered before trying to maximize parallel work. Once these principles are understood, Java concurrency becomes much easier to apply to real-world systems.

Code Examples

java
class Worker implements Runnable {

    @Override
    public void run() {

        for (int i = 1; i <= 5; i++) {

            System.out.println(
                Thread.currentThread().getName()
                    + " -> "
                    + i
            );
        }
    }
}

public class RunnableDemo {

    public static void main(String[] args) {

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

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

        first.start();
        second.start();
    }
}
    
java
class Counter {

    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

public class SynchronizationDemo {

    public static void main(String[] args)
        throws InterruptedException {

        Counter counter =
            new Counter();

        Thread first =
            new Thread(() -> {

                for (int i = 0; i < 1000; i++) {
                    counter.increment();
                }
            });

        Thread second =
            new Thread(() -> {

                for (int i = 0; i < 1000; i++) {
                    counter.increment();
                }
            });

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

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

        System.out.println(
            "Final count: "
                + counter.getCount()
        );
    }
}
    
java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorServiceDemo {

    public static void main(String[] args) {

        ExecutorService executor =
            Executors.newFixedThreadPool(3);

        for (int i = 1; i <= 6; i++) {

            final int taskId = i;

            executor.submit(() -> {

                System.out.println(
                    "Task "
                        + taskId
                        + " running on "
                        + Thread.currentThread()
                            .getName()
                );
            });
        }

        executor.shutdown();
    }
}
    
java
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableFutureDemo {

    public static void main(String[] args)
        throws Exception {

        ExecutorService executor =
            Executors.newFixedThreadPool(2);

        Callable<Integer> task = () -> {

            int first = 20;
            int second = 22;

            return first + second;
        };

        Future<Integer> future =
            executor.submit(task);

        System.out.println(
            "Doing other work..."
        );

        int result =
            future.get();

        System.out.println(
            "Result: " + result
        );

        executor.shutdown();
    }
}
    
java
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class ConcurrentCollectionsDemo {

    public static void main(String[] args) {

        ConcurrentHashMap<String, AtomicInteger> counts =
            new ConcurrentHashMap<>();

        counts
            .computeIfAbsent(
                "Java",
                key -> new AtomicInteger()
            )
            .incrementAndGet();

        counts
            .computeIfAbsent(
                "Java",
                key -> new AtomicInteger()
            )
            .incrementAndGet();

        System.out.println(
            counts.get("Java").get()
        );
    }
}
    
java
import java.util.concurrent.CompletableFuture;

public class CompletableFutureDemo {

    public static void main(String[] args) {

        CompletableFuture<String> result =
            CompletableFuture
                .supplyAsync(
                    () -> "Java"
                )
                .thenApply(
                    value ->
                        value + " Concurrency"
                )
                .thenApply(
                    String::toUpperCase
                );

        System.out.println(
            result.join()
        );
    }
}
    
java
public class VirtualThreadDemo {

    public static void main(String[] args)
        throws InterruptedException {

        Thread thread =
            Thread.startVirtualThread(() -> {

                System.out.println(
                    "Task running on a virtual thread"
                );
            });

        thread.join();
    }
}
    

Pro Tip

Do not start with threads just because a task can run in parallel. First identify which work is independent, which state is shared, and what guarantees the application needs. Then choose the simplest concurrency tool that correctly solves the problem.

More Advanced Java lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.