Fortgeschrittenes Java Tag 5: Multithreading und Parallelität

Ziel dieses Tages

Heute lernst du:

Am Ende wirst du sichere nebenläufige Programme in Java schreiben können.

Schritt 1: Threads erstellen

Du kannst Threads mit Runnable oder Thread erstellen.


Runnable task = () -> System.out.println("Läuft im Thread " + Thread.currentThread().getName());
Thread thread = new Thread(task);
thread.start();

Schritt 2: ExecutorService verwenden

Thread-Pools helfen dabei, mehrere Threads effizient zu verwalten.


import java.util.concurrent.*;

ExecutorService executor = Executors.newFixedThreadPool(2);

Runnable task = () -> System.out.println("Läuft im Thread " + Thread.currentThread().getName());

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

Schritt 3: Synchronisation und Locks

Verwende synchronized oder ReentrantLock, um Race Conditions zu vermeiden.


class Counter {
    private int count = 0;

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

    public int getCount() {
        return count;
    }
}

Schritt 4: Häufige Concurrency-Probleme

Übung


import java.util.concurrent.*;

ExecutorService executor = Executors.newFixedThreadPool(2);

Runnable task = () -> System.out.println("Läuft im Thread " + Thread.currentThread().getName());

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

Aufgabe

Erstelle zwei Threads, die einen gemeinsamen Zähler sicher mit Synchronisation erhöhen.

Schritte:

Beispiel:


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("Finaler Zählerwert: " + counter.getCount());
    }
}