環境說明
源碼
public class VolatileAtomicDemo {
public static volatile int counter = 0;
public static void increase() {
counter++;
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 1_000; j++) {
increase();
}
});
threads[i].start();
}
for (Thread thread : threads) {
thread.join();
}
System.out.printf("最後counter的數值爲:%d", counter);
}
}
輸出結果
最後counter的數值爲:8733
加上synchronized修飾後
public static void increase() {
synchronized (Object.class) {
counter++;
}
}
加上synchronized後的輸出結果
最後counter的數值爲:10000