-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTestCAS.java
More file actions
35 lines (32 loc) · 779 Bytes
/
TestCAS.java
File metadata and controls
35 lines (32 loc) · 779 Bytes
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
package com.jucday01;
public class TestCAS {
public static void main(String[] args) {
final CompareAndSwap cas=new CompareAndSwap();
for(int i=0;i<10;i++){
new Thread(new Runnable() {
@Override
public void run() {
int ev=cas.get();
boolean b=cas.compareandSet(ev, (int)(Math.random()*101));
System.out.println(b);
}
}).start();
}
}
}
class CompareAndSwap{
private int value;
public synchronized int get() {
return value;
}
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);
}
}