Created
January 16, 2018 16:34
-
-
Save freyacodes/db54d1b53d3a214f9ddb9f8ef3afb7ae to your computer and use it in GitHub Desktop.
Normal int, volatile int, and AtomicInteger thread safety comparison
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 scratch extends Thread { | |
public static int x = 0; | |
public static volatile int y = 0; | |
public static AtomicInteger z = new AtomicInteger(0); | |
public static void main(String[] args) { | |
for (int i = 0; i < 1000; i++) { | |
new scratch().start(); | |
} | |
try { | |
Thread.sleep(5000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
System.out.printf("x: %d\ny: %d\nz: %d", x, y, z.get()); | |
} | |
@Override | |
public void run() { | |
for (int i = 0; i < 10000; i++) { | |
x++; | |
y++; | |
z.incrementAndGet(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment