证明在32位hotspot上,long不是原子操作
2016-07-24 21:57
459 查看
`public class UnatomicLong implements Runnable {
private static long test = 0;
}`
结果为:
1111111111111111111111111111111111111111111111111111111111111111
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000011111111111111111111111111111111
4294967295
private static long test = 0;
private final long val; public UnatomicLong(long val) { this.val = val; } @Override public void run() { while (!Thread.interrupted()) { test = val; // 两个线程都试图将自己的私有变量val赋值给类私有静态变量test } } public static void main(String[] args) { Thread t1 = new Thread(new UnatomicLong(-1)); Thread t2 = new Thread(new UnatomicLong(0)); System.out.println(Long.toBinaryString(-1)); System.out.println(pad(Long.toBinaryString(0), 64)); t1.start(); t2.start(); long val; while ((val = test) == -1 || val == 0) { // 如果静态成员test的值是-1或0,说明两个线程操作没有交叉 } System.out.println(pad(Long.toBinaryString(val), 64)); System.out.println(val); t1.interrupt(); t2.interrupt(); } // prepend 0s to the string to make it the target length private static String pad(String s, int targetLength) { int n = targetLength - s.length(); for (int x = 0; x < n; x++) { s = "0" + s; } return s; }
}`
结果为:
1111111111111111111111111111111111111111111111111111111111111111
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000011111111111111111111111111111111
4294967295
相关文章推荐
- Spring的简单定时任务的实现
- HTTP Status 500 - Servlet.init() for servlet springMVC threw exception
- 字符集合---- 华为2016研发工程师编程题
- Android开发中需要注意哪些坑
- Scala的var,val
- javaweb回顾第六篇谈一谈Servlet线程安全问题
- ReLU 和sigmoid 函数对比
- iPhone白苹果怎么办?白苹果各种解决办法方法
- 【Codeforces 604A】Uncowed Forces
- 个性水彩人像效果
- 【学习笔记】让一个块级元素上下左右居中 ps:初学者求轻虐
- 【源码】LinkedHashMap源码剖析
- [bzoj1369][Baltic2003]Gem(树上dp)
- linux安装yum源
- CSDN博客常见问题
- Codeforces Round #131 (Div. 1) B. Numbers dp
- Chrome 控制台console的用法
- Chromium Embedded Framework 中文文档(简介)
- C#枚举和结构体
- 在MacBook Pro上装Mac和Linux双系统