Skip to content

Commit 77d09cc

Browse files
committed
volatile的不能保证原子性代码
1 parent b834148 commit 77d09cc

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @program JavaBooks
3+
* @description: 不能保证原子
4+
* @author: mf
5+
* @create: 2020/02/13 01:16
6+
*/
7+
8+
package com.juc.volatiletest;
9+
10+
public class VolatileAtomicDemo {
11+
public static volatile int count = 0;
12+
13+
public static void increase() {
14+
count++;
15+
}
16+
17+
public static void main(String[] args) {
18+
Thread[] threads = new Thread[20];
19+
for(int i = 0; i < threads.length; i++) {
20+
threads[i] = new Thread(() -> {
21+
for(int j = 0; j < 1000; j++) {
22+
increase();
23+
}
24+
});
25+
threads[i].start();
26+
}
27+
//等待所有累加线程结束
28+
while (Thread.activeCount() > 1) {
29+
Thread.yield();
30+
}
31+
System.out.println(count);
32+
}
33+
}

0 commit comments

Comments
 (0)