volatile、非volatile、Atomic计数器比较
2016-04-11 15:56
253 查看
import java.util.concurrent.atomic.AtomicInteger; public class Atomicity { private static volatile int nonAtomicCounter = 0; private static long nonVolNonAtomicCountter = 0; private static volatile AtomicInteger atomicCounter = new AtomicInteger(0); private static int times = 0; //对单个的普通 变量的写用同一个监视器同步 public static synchronized void set(long l) { nonVolNonAtomicCountter = l; } //对单个的普通变量的读用同一个监视器同步 public static synchronized long get() { return nonVolNonAtomicCountter; } public static void getAndIncrement () { //普通方法调用 long temp = get(); //调用已同步的读方法 temp += 1L; //普通写操作 set(temp); //调用已同步的写方法 } public static void caculate() { times++; for (int i = 0; i < 1000; i++) { new Thread(new Runnable() { @Override public void run() { getAndIncrement(); nonAtomicCounter++; atomicCounter.incrementAndGet(); } }).start(); } try { Thread.sleep(1000); } catch (InterruptedException e) { } } public static void main(String[] args) { caculate(); while (nonVolNonAtomicCountter == 1000) { nonAtomicCounter = 0; atomicCounter.set(0); set(0); caculate(); } System.out.println("nonVolNonAtomicCountter: " + times + ":" + nonVolNonAtomicCountter); System.out.println("Non-atomic counter: " + times + ":" + nonAtomicCounter); System.out.println("Atomic counter: " + times + ":" + atomicCounter); } }
result :
nonVolNonAtomicCountter: 16:999
Non-atomic counter: 16:1000
Atomic counter: 16:1000
所以:volatile和加监视器都不能实现原子操作。volatile仅能保证从主内存读到线程内存是最新的值。
相关文章推荐
- lintcode: Edit Distance
- mysql 函数 find in set()
- android textview xml 属性设置
- Ubuntu 软件包管理工具 dpkg, APT 的一些命令
- iOS闪退(崩溃)手动再符号化解析
- VMware Horizon FLEX介绍
- spring配置文件详解
- IO负载高的来源定位
- eclipse集成的maven插件下载java源码
- Lua 与 C混合编程
- 给TextView加边框
- 在页面关闭或者刷新的时候触发 onbeforeunload
- Linux系统信息查看命令
- Netty in Action (三)第一章节 第二部分 Netty简介
- JVM内存解析 笔记联想
- LeetCode 137 -Single Number II ( JAVA )
- oracle 基本查询
- 利用简洁的图片预加载组件提升h5移动页面的用户体验
- javascript HTML5 Canvas实现圆盘抽奖功能
- decimal double