You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit fd5e9a4
Browse filesBrowse the repository at this point in the historyBrowse files
在没有锁的机制下需要字段 value 要借助 volatile 原语,保证线程间的数据是可见的。这样在获取变量的值的时候才能直接读取。然后来看看 `++i` 是怎么做到的。`getAndIncrement` 采用了 CAS 操作,每次从内存中读取数据然后将此数据和 `+1` 后的结果进行 CAS 操作,如果成功就返回结果,否则重试直到成功为止。而 `compareAndSet` 利用 JNI 来完成 CPU 指令的操作。
// static variable pointing to instance of MySharedObject
9
+
publicstaticfinalMySharedObject sharedInstance =
10
+
newMySharedObject();
11
+
12
+
// member variables pointing to two objects on the heap
13
+
publicInteger object2 =newInteger(22);
14
+
publicInteger object4 =newInteger(44);
15
+
16
+
publiclong member1 =12345;
17
+
publiclong member1 =67890;
18
+
}
19
+
20
+
publicclassMyRunnableimplementsRunnable() {
21
+
22
+
publicvoidrun() {
23
+
methodOne();
24
+
}
25
+
26
+
publicvoidmethodOne() {
27
+
int localVariable1 =45;
28
+
29
+
MySharedObject localVariable2 =
30
+
MySharedObject.sharedInstance;
31
+
32
+
//... do more with local variables.
33
+
34
+
methodTwo();
35
+
}
36
+
37
+
publicvoidmethodTwo() {
38
+
Integer localVariable1 =newInteger(99);
39
+
40
+
//... do more with local variable.
41
+
}
42
+
}
43
+
```
44
+
5
45
# volatile
6
46
7
47
Java 中的 volatile 关键字主要即是保证了变量的可见性,而不是原子性。JVM 中每一个变量都有一个主内存,为了保证最佳性能,JVM 允许线程从主内存拷贝一份私有拷贝,然后在线程读取变量的时候从主内存里面读,退出的时候,将修改的值同步到主内存。形象而言,对于变量 t,A 线程对 t 变量修改的值,对 B 线程是可见的。但是 A 获取到 t 的值加 1 之后,突然挂起了,B 获取到的值还是最新的值,volatile 能保证 B 能获取到的 t 是最新的值,因为 A 的 t+1 并没有写到主内存里面去。
0 commit comments