parallele-programmierung/u06-4/AtomicCounterTest.java

31 lines
1012 B
Java

public class AtomicCounterTest {
private static final int N_THREADS = 100;
private static final int INCREMENT = 1_000_000;
private static void incCounter(AtomicCounter atomicCounter) {
for (int i= 0; i < INCREMENT; ++i) {
atomicCounter.updateAndGet(x -> x+1);
}
}
public static void main(String[] args) {
AtomicCounter atomicCounter = new AtomicCounter();
Thread[] threads = new Thread[N_THREADS];
for (int i = 0; i < N_THREADS; ++i) {
Thread incrementer = new Thread(()-> incCounter(atomicCounter));
incrementer.start();
threads[i] = incrementer;
}
for (Thread incrementer: threads) {
try {
incrementer.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Counter value = " +
atomicCounter.updateAndGet(x -> x) + // only to get, not to change
" and that is" +
(atomicCounter.updateAndGet(x -> x) == N_THREADS * INCREMENT ? "" : "NOT") +
" correct.");
}
}