Advanced Java Day 5: Multithreading and Concurrency

Goal of this Day

Today you will learn:

By the end, you will be able to write safe concurrent programs in Java.

Step 1: Creating Threads

You can create threads using Runnable or Thread.


Runnable task = () -> System.out.println("Running in thread " + Thread.currentThread().getName());
Thread thread = new Thread(task);
thread.start();

Step 2: Using ExecutorService

Thread pools help manage multiple threads efficiently.


import java.util.concurrent.*;

ExecutorService executor = Executors.newFixedThreadPool(2);

Runnable task = () -> System.out.println("Running in thread " + Thread.currentThread().getName());

executor.submit(task);
executor.shutdown();

Step 3: Synchronization and Locks

Use synchronized or ReentrantLock to avoid race conditions.


class Counter {
    private int count = 0;

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

    public int getCount() {
        return count;
    }
}

Step 4: Common Concurrency Problems

Practice


import java.util.concurrent.*;

ExecutorService executor = Executors.newFixedThreadPool(2);

Runnable task = () -> System.out.println("Running in thread " + Thread.currentThread().getName());

executor.submit(task);
executor.shutdown();

Exercise

Create two threads that increment a shared counter safely using synchronization.

Steps:

Example:


class Counter {
    private int count = 0;

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

    public int getCount() {
        return count;
    }
}

public class SafeCounterExample {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

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

        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);

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

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

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