Created
January 16, 2018 16:34
Normal int, volatile int, and AtomicInteger thread safety comparison
This file contains hidden or 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