Java-Thread-Safe-Zähler

Lerne ich schreiben-thread-safe-Programme und wie bewerten Sie codes, die nicht threadsicher sind.

Einer Klasse wird als thread-sicher, wenn es richtig funktioniert, wenn die Ausführung durch mehrere threads.

Meine Counter.java ist nicht thread-sicher ist, aber die Ausgabe war gedruckt, wie erwartet von 0-9 für alle 3 threads.

Kann jemand erklärt warum? und wie thread-Sicherheit funktioniert?

public class Counter {

    private int count = 0;

    public void increment() {
        count++;
    }

    public void decrement() {
        count--;
    }

    public void print() {
        System.out.println(count);
    }

}

public class CountThread extends Thread {
    private Counter counter = new Counter();

    public CountThread(String name) {
        super(name);
    }

    public void run() {
        for (int i=0; i<10; i++) {
            System.out.print("Thread " + getName() + " ");
            counter.print();
            counter.increment();
        }
    }

}

public class CounterMain {

    public static void main(String[] args) {
        CountThread threadOne = new CountThread("1");
        CountThread threadTwo = new CountThread("2");
        CountThread threadThree = new CountThread("3");

        threadOne.start();
        threadTwo.start();
        threadThree.start();
    }

}
  • Sie sind mit einem anderen Counter-Objekt in jedem thread so, dass ist der Grund, warum sieht man keine thread-Sicherheit Probleme in diesem Fall.
InformationsquelleAutor ilovetolearn | 2013-04-06
Schreibe einen Kommentar