Skip to content

Instantly share code, notes, and snippets.

@tlehman
Created November 3, 2017 20:28
Show Gist options
  • Save tlehman/34520e469f29a9360476617fb08d745a to your computer and use it in GitHub Desktop.
Save tlehman/34520e469f29a9360476617fb08d745a to your computer and use it in GitHub Desktop.
Atomic integer multithreaded example
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; }
}
}
@tlehman
Copy link
Author

tlehman commented Nov 3, 2017

When I run this on my 4-core machine, I get:

$ javac AtomicIntegerExample.java && java AtomicIntegerExample
The atomic integer should be 400000, it is 400000
The non-atomic integer should be 400000, it is 295007

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment