import java.util.concurrent.atomic.*; class Counter { int x = 0; /* "synchonized" auskommentieren, um Race-conditions zu sehen drinnen lassen, um die Langsamkeit von Synchronisation zu messen das hier ist allerdings ein Extremfall fuer Synchronsation */ public synchronized void increment() { x++; } public int get() { return x; } } class Worker implements Runnable { private Counter counter; public Worker (Counter c) { counter = c; } public void run() { for(int i = 0; i < 100000000; i++) counter.increment(); } } public class counter { public static final void main (String[] args) { Counter c1 = new Counter(); Worker w1 = new Worker(c1); Worker w2 = new Worker(c1); if (false) { /* true fuer sequentielle Ausfuehrung */ w1.run(); w2.run(); } else { Thread t1 = new Thread(w1); Thread t2 = new Thread(w2); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException x) { } } System.out.println("c1: x = " + c1.get()); } }