volation 关键字不具备->原子性 使用原子性需使用Atomic 序列类
package com.dt.test;
import java.util.concurrent.atomic.AtomicInteger;
public class Test {
// private static volatile int count = 0; 非原子性
private static AtomicInteger count = new AtomicInteger(0);
private static void inc() {
// 这里延迟1毫秒,使得结果明显
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
// count++;
count.incrementAndGet();
}
public static void main(String[] args) {
// 同时启动1000个线程,去进行i++计算,看看实际结果
for (int i = 0; i < 1000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
Test.inc();
}
}).start();
}
// 这里每次运行的值都有可能不同,可能为1000
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("运行结果:Counter.count=" + Test.count);
}
}