Java Multithreading
100%

Java Multithreading

Multithreading is a Java feature that allows multiple threads to execute within the same program. A thread is a lightweight unit of execution.

Multithreading is useful for tasks such as downloading files, processing data, handling user requests, and running background operations while the main program continues.

1. What Is a Thread?

A thread is a separate path of execution inside a program. Every Java application starts with a main thread that executes the main() method.

public class Main {
    public static void main(String[] args) {
        System.out.println("Main thread is running");
    }
}
Output:
Main thread is running

In this example, the main thread executes the statement inside the main() method.

2. Creating a Thread by Extending Thread

One way to create a thread is to extend the Thread class and override its run() method.

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running");
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();

        t1.start();
    }
}
Output:
Thread is running

start() starts a new thread, which then executes the run() method.

Calling run() directly does not start a new thread. Use start() to begin a separate thread of execution.
3. Creating a Thread by Implementing Runnable

Another common approach is to implement the Runnable interface. This separates the task from the thread that runs it.

class MyTask implements Runnable {
    public void run() {
        System.out.println("Runnable task is running");
    }
}

public class Main {
    public static void main(String[] args) {
        MyTask task = new MyTask();

        Thread t1 = new Thread(task);
        t1.start();
    }
}
Output:
Runnable task is running

Implementing Runnable is often preferable when your class needs to extend another class.

4. Running Multiple Threads

You can create multiple threads to perform different tasks. The JVM and operating system determine when each thread executes.

class MyThread extends Thread {
    public void run() {
        for (int i = 1; i <= 3; i++) {
            System.out.println(
                Thread.currentThread().getName() + ": " + i
            );
        }
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();

        t1.start();
        t2.start();
    }
}
Possible Output:
Thread-0: 1
Thread-1: 1
Thread-0: 2
Thread-0: 3
Thread-1: 2
Thread-1: 3
The output order is not guaranteed. Your program may display the lines in a different order.
5. Using the sleep() Method

The Thread.sleep() method pauses the current thread for a specified time. The duration is measured in milliseconds.

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

        for (int i = 1; i <= 3; i++) {
            System.out.println(i);

            Thread.sleep(1000);
        }
    }
}
Output:
1
2
3

The program pauses for approximately one second after each printed number.

Thread.sleep() can throw InterruptedException. This example declares it using throws InterruptedException.
6. Using the join() Method

The join() method makes the calling thread wait until the specified thread finishes.

class MyThread extends Thread {
    public void run() {
        System.out.println("Child thread finished");
    }
}

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

        MyThread t1 = new MyThread();

        t1.start();
        t1.join();

        System.out.println("Main thread continues");
    }
}
Output:
Child thread finished
Main thread continues

Because the main thread calls join(), it waits for t1 to finish before printing the second message.

7. Thread Names and Priorities

Java allows you to set thread names and priorities. Priorities are scheduling hints and do not guarantee execution order.

class MyThread extends Thread {
    public void run() {
        System.out.println(
            "Thread name: " + Thread.currentThread().getName()
        );
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();

        t1.setName("WorkerThread");
        t1.setPriority(Thread.NORM_PRIORITY);

        t1.start();
    }
}
Output:
Thread name: WorkerThread

Java provides these common priority constants:

  • Thread.MIN_PRIORITY — 1
  • Thread.NORM_PRIORITY — 5
  • Thread.MAX_PRIORITY — 10
8. Thread Life Cycle

A Java thread can move through several states during its lifetime.

State Description
NEW The thread has been created but not started.
RUNNABLE The thread is ready to run or is running.
BLOCKED The thread is waiting to acquire a monitor lock.
WAITING The thread is waiting indefinitely for another action.
TIMED_WAITING The thread is waiting for a limited time.
TERMINATED The thread has finished execution.
class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running");
    }
}

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

        MyThread t1 = new MyThread();

        System.out.println(t1.getState());

        t1.start();
        t1.join();

        System.out.println(t1.getState());
    }
}
Output:
NEW
Thread is running
TERMINATED
9. Synchronization in Java

When multiple threads access shared data, their operations may interfere with each other. The synchronized keyword can protect a critical section so only one thread at a time executes it using the same monitor lock.

class Counter {
    private int count = 0;

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

    public int getCount() {
        return count;
    }
}

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

        Counter counter = new Counter();

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

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

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println(counter.getCount());
    }
}
Output:
2000

Both threads share the same counter. Synchronization protects the increment operation from lost updates.

10. The volatile Keyword

The volatile keyword helps ensure that threads see the latest value of a shared variable. It does not make compound operations such as count++ atomic.

class SharedData {
    volatile boolean running = true;
}

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

        SharedData data = new SharedData();

        Thread worker = new Thread(() -> {
            while (data.running) {
                // Wait while running is true.
            }

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

        worker.start();

        Thread.sleep(100);
        data.running = false;

        worker.join();
    }
}
Output:
Worker stopped

Here, the volatile field allows the worker thread to observe the updated flag. In real applications, avoid busy-waiting when a more suitable coordination method is available.

11. Using ExecutorService

For many applications, an executor is a better way to manage tasks than manually creating a new thread for every task. An executor can reuse threads from a pool.

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

public class Main {
    public static void main(String[] args) {
        ExecutorService executor =
            Executors.newFixedThreadPool(2);

        executor.submit(() -> {
            System.out.println("Task 1 is running");
        });

        executor.submit(() -> {
            System.out.println("Task 2 is running");
        });

        executor.shutdown();
    }
}
Possible Output:
Task 1 is running
Task 2 is running
The order of the two messages is not guaranteed. shutdown() stops accepting new tasks while allowing submitted tasks to finish.
12. Important Thread Methods
Method Purpose
start() Starts a new thread of execution.
run() Contains the task executed by a thread.
sleep() Pauses the current thread for a specified time.
join() Waits for another thread to finish.
getName() Gets the thread name.
setName() Sets the thread name.
getState() Returns the current thread state.
isAlive() Checks whether a thread has started and not yet terminated.
13. Java Multithreading Assignments
  1. Create a thread by extending the Thread class.
  2. Create a thread by implementing the Runnable interface.
  3. Create two threads that print numbers from 1 to 5.
  4. Use Thread.sleep() to pause a thread for one second.
  5. Use join() to make the main thread wait for a worker thread.
  6. Set a custom thread name and print it.
  7. Display the state of a thread before starting and after finishing.
  8. Create two threads that safely increment a shared counter using synchronization.
  9. Use a volatile boolean flag to signal a worker thread to stop.
  10. Use ExecutorService to execute three tasks.

Quick Quiz: Java Multithreading

Select the correct answer for each question.

1. Which method starts a new thread?



2. Which method makes one thread wait for another thread to finish?



3. What is the purpose of synchronization?