Module 13 of 30 · Java Programming — Core to Enterprise · Intermediate

Multithreading

Duration: 7 min

This module delves into the world of multithreading in Java, a crucial aspect for building efficient and responsive applications. We will explore how to create and manage threads, understand thread synchronization, and learn about thread pools. Mastering multithreading is essential for developing high-performance enterprise applications.

Creating and Managing Threads

Visual Guide: This module includes diagrams and flowcharts. Check the course materials for detailed visualizations.

In Java, threads can be created by extending the Thread class or implementing the Runnable interface. The Thread class provides methods to start, stop, and manage threads. Creating a thread by implementing Runnable is often preferred as it avoids class inheritance limitations.

public class Example1 {
    public static void main(String[] args) {
        // Creating a thread by implementing Runnable
        Runnable task = () -> {
            for (int i = 1; i <= 5; i++) {
                System.out.println("Task executed by thread: " + Thread.currentThread().getName() + " - Count: " + i);
                try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
            }
        };

        // Creating threads and starting them
        Thread thread1 = new Thread(task, "Thread-1");
        Thread thread2 = new Thread(task, "Thread-2");

        thread1.start();
        thread2.start();
    }
}
Task executed by thread: Thread-1 - Count: 1
Task executed by thread: Thread-2 - Count: 1
Task executed by thread: Thread-1 - Count: 2
Task executed by thread: Thread-2 - Count: 2
...

Thread Synchronization

Thread synchronization is vital to prevent data inconsistency when multiple threads access shared resources. Java provides the synchronized keyword and the Lock interface to manage thread synchronization. Synchronized methods or blocks ensure that only one thread can execute them at a time.

public class Example2 {
    private int counter = 0;

    public synchronized void increment() {
        counter++;
        System.out.println("Counter incremented by " + Thread.currentThread().getName() + " - New value: " + counter);
    }

    public static void main(String[] args) {
        Example2 example = new Example2();

        Runnable task = () -> {
            for (int i = 0; i < 5; i++) {
                example.increment();
                try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }
            }
        };

        Thread thread1 = new Thread(task, "Thread-1");
        Thread thread2 = new Thread(task, "Thread-2");

        thread1.start();
        thread2.start();
    }
}

💡 Tip: Avoid using synchronized on large blocks of code or methods to prevent performance bottlenecks. Instead, synchronize only the critical sections that access shared resources.

❓ How can you create a thread in Java?

❓ What is the purpose of the synchronized keyword in Java?

← Previous Continue interactively → Next →

Related Courses