Skip to main content
Java Basics
CHAPTER 23 Beginner

Multithreading in Java

Updated: May 17, 2026
5 min read

# CHAPTER 23

Multithreading in Java

1. Introduction

Modern applications must do multiple things simultaneously — downloading a file while updating the UI, serving thousands of web requests at once. Multithreading allows Java programs to execute multiple tasks (threads) concurrently within a single process.

2. Creating Threads

Method 1: Extending Thread

java
123456789101112
class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
            try { Thread.sleep(500); } catch (InterruptedException e) {}
        }
    }
}

MyThread t1 = new MyThread();
t1.start(); // start(), NOT run()!

Method 2: Implementing Runnable (Preferred)

java
123456789
class MyTask implements Runnable {
    @Override
    public void run() {
        System.out.println("Task running on: " + Thread.currentThread().getName());
    }
}

Thread t = new Thread(new MyTask());
t.start();

Method 3: Lambda (Java 8+)

java
12
Thread t = new Thread(() -> System.out.println("Lambda thread!"));
t.start();

3. Thread Lifecycle

12
NEW → RUNNABLE → RUNNING → (BLOCKED/WAITING) → TERMINATED
      (start)    (scheduler)                      (run() completes)

4. Thread Methods

MethodDescription
start()Starts the thread
run()Contains the code to execute
sleep(ms)Pauses for milliseconds
join()Waits for thread to finish
getName()Gets thread name
setPriority(n)Sets priority (1-10)
isAlive()Checks if thread is running

5. Synchronization

When multiple threads access shared data, race conditions can corrupt it:
java
1234567
class Counter {
    private int count = 0;
    
    synchronized void increment() { count++; }
    
    int getCount() { return count; }
}

The synchronized keyword ensures only ONE thread can execute the method at a time.

6. Thread Safety with Synchronized Block

java
123456789101112
class BankAccount {
    private double balance = 1000;
    
    void withdraw(double amount) {
        synchronized (this) {
            if (balance >= amount) {
                balance -= amount;
                System.out.println("Withdrew: " + amount + " | Remaining: " + balance);
            }
        }
    }
}

7. ExecutorService (Modern Approach)

java
123456789101112
import java.util.concurrent.*;

ExecutorService executor = Executors.newFixedThreadPool(3);

for (int i = 0; i < 5; i++) {
    final int task = i;
    executor.submit(() -> {
        System.out.println("Task " + task + " on " + Thread.currentThread().getName());
    });
}

executor.shutdown();

8. MCQ Quiz with Answers

Question 1

Which method starts a thread?

Question 2

Runnable interface has which method?

Question 3

synchronized prevents:

Question 4

Thread.sleep() does what?

Question 5

join() makes the calling thread:

Question 6

Which is preferred: Thread class or Runnable?

Question 7

ExecutorService manages:

Question 8

A deadlock occurs when:

Question 9

Thread priority range is:

Question 10

Can main() run on a thread?

9. Summary

Multithreading enables concurrent execution. Create threads by extending Thread or implementing Runnable. Synchronization prevents race conditions on shared data. ExecutorService provides modern thread pool management. Always handle thread safety carefully to avoid deadlocks.

10. Next Chapter Recommendation

In Chapter 24: Java JDBC and Database Connectivity, we'll connect Java to MySQL databases for real-world data persistence.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·