Created
November 3, 2017 20:28
-
-
Save tlehman/34520e469f29a9360476617fb08d745a to your computer and use it in GitHub Desktop.
Atomic integer multithreaded example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.atomic.AtomicInteger; | |
public class AtomicIntegerExample { | |
public static void main(String args[]) throws InterruptedException { | |
AtomicInteger a = new AtomicInteger(); | |
NonAtomicInteger n = new NonAtomicInteger(); | |
Runnable r = () -> { | |
for(int j = 0; j < 100_000; j++) { | |
a.getAndIncrement(); | |
n.getAndIncrement(); | |
} | |
}; | |
Thread t1 = new Thread(r); | |
Thread t2 = new Thread(r); | |
Thread t3 = new Thread(r); | |
Thread t4 = new Thread(r); | |
t1.start(); | |
t2.start(); | |
t3.start(); | |
t4.start(); | |
t1.join(); | |
t2.join(); | |
t3.join(); | |
t4.join(); | |
System.out.printf("The atomic integer should be 400000, it is %d\n", a.get()); | |
System.out.printf("The non-atomic integer should be 400000, it is %d\n", n.get()); | |
} | |
public static class NonAtomicInteger { | |
private int i = 0; | |
public NonAtomicInteger() { i = 0; } | |
public int getAndIncrement() { return i++; } | |
public int get() { return i; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When I run this on my 4-core machine, I get: