u06-4
This commit is contained in:
parent
d4a1dd55e9
commit
d9d276b0c9
|
@ -0,0 +1,22 @@
|
|||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.IntUnaryOperator;
|
||||
|
||||
class AtomicCounter {
|
||||
private AtomicInteger i;
|
||||
|
||||
public AtomicCounter() {
|
||||
this.i = new AtomicInteger(0);
|
||||
};
|
||||
|
||||
public int updateAndGet(IntUnaryOperator op) {
|
||||
// not safe if op is not a pure function
|
||||
|
||||
int oldVal;
|
||||
|
||||
do {
|
||||
oldVal = i.get();
|
||||
} while (!i.compareAndSet(oldVal, op.applyAsInt(oldVal)));
|
||||
|
||||
return op.applyAsInt(oldVal);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
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.");
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue