Java中自增自减在JVM中的体现
Java中自增自减操作底层并不是原子操作(以静态变量为例),多线程情况下容易出现共享安全问题
i++
1 2 3 4
| getstatic i iconst_1 iadd putstatic i
|
i–
1 2 3 4
| getstatic i iconst_1 isub putstatic i
|
共享操作代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| static int counter = 0; public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(() -> { for (int i = 0; i < 5000; i++) { counter++; } }, "t1"); Thread t2 = new Thread(() -> { for (int i = 0; i < 5000; i++) { counter--; } }, "t2"); t1.start(); t2.start(); t1.join(); t2.join(); log.debug("{}",counter); }
|
单线程情况(运行正常)
多线程情况(运行异常)