import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicTest {
public static void main(String[] args) {
// 使用Atomic的原子性保证多线程安全
final AtomicInteger count = new AtomicInteger();
// 使用线程池初始化3个线程模拟并发环境
ExecutorService executorService = Executors.newFixedThreadPool(3);
for(int i=0;i<20;i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
// count每次自增1并输出
System.out.println(count.incrementAndGet());
}
});
}
// 关闭线程池
executorService.shutdown();
}
}
运行后输出结果如下,说明在并发情况下确保了线程安全