-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestCompareAndSwap.java
More file actions
50 lines (45 loc) · 1.25 KB
/
TestCompareAndSwap.java
File metadata and controls
50 lines (45 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.zyj;
/**
* 版权声明:CopyRight (c) 2018 ucarinc. All Rights Reserved.
*
* @author : 张勇杰
* @date : 2019/2/22 9:46
* @Version : v1.0
* @description
**/
public class TestCompareAndSwap {
public static void main(String[] args) {
final CompareAndSwap compareAndSwap=new CompareAndSwap();
for(int i = 0 ;i<5;i++){
new Thread(new Runnable() {
@Override
public void run() {
int expectedValue = compareAndSwap.get();
System.out.println(compareAndSwap.compareAndSet(expectedValue,(int)(Math.random()*101)));
}
}).start();
}
}
}
class CompareAndSwap{
private int value;
public synchronized int get(){
return value;
}
/**
* 比较
* @param expectedValue
* @param newValue
* @return
*/
public synchronized int compareAndSwap(int expectedValue,int newValue){
int oldValue = value;
if(oldValue == expectedValue){
this.value = newValue;
}
return oldValue;
}
public synchronized boolean compareAndSet(int expectedValue,int newValue){
return expectedValue == compareAndSwap(expectedValue,newValue);
}
}