File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
src/main/java/com/example/concurrency/atomic Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .example .concurrency .atomic ;
2
+
3
+ /**
4
+ * 描述:
5
+ * SimulatedCAS
6
+ *
7
+ * @author zed
8
+ * @since 2019-06-18 2:09 PM
9
+ */
10
+ public class SimulatedCAS {
11
+ private int count ;
12
+
13
+ /**
14
+ * 实现 count+=1
15
+ * @param newValue new
16
+ */
17
+ void addOne (int newValue ){
18
+ //自旋
19
+ do {
20
+ newValue = count +1 ;
21
+ }while (count != cas (count ,newValue ));
22
+ }
23
+ /**
24
+ * 只有当目前 count 的值和期望值 expect 相等时,才会将 count 更新为 newValue。
25
+ * @param expect 期望值
26
+ * @param newValue 更新值
27
+ * @return 旧值
28
+ */
29
+ synchronized int cas (
30
+ int expect , int newValue ){
31
+ // 读目前 count 的值
32
+ int curValue = count ;
33
+ // 比较目前 count 值是否 == 期望值
34
+ if (curValue == expect ){
35
+ // 如果是,则更新 count 的值
36
+ count = newValue ;
37
+ }
38
+ // 返回写入前的值
39
+ return curValue ;
40
+ }
41
+ }
42
+
You can’t perform that action at this time.
0 commit comments