volatile本身不保证获取和设置操作的原子性,仅仅保持修改的可见性 。但是java的内存模型保证声明为volatile的long和double变量的get和set操作是原子的 。
(from /topic/213794) 举个例子来说:(example is from /questions/17481153/long-and-double-assignments-are-not-atomic-how-does-it-matter) public class UnatomicLong implements Runnable { 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; } } 。
【long类型怎么写】
文章插图
- shouts的音标怎么写
- instruments音标怎么写
- 三国时期的马字怎么写
- 九百元的繁体字怎么写
- 9点35分用英语怎么写
- 0到9的笔顺怎么写
- 笑容的容字怎么写
- 探出了头的探怎么写
- 恼的笔画顺序怎么写
- 蚧的拼音怎么写