java,
分享于 点击 15948 次 点评:80
java,
class CasNumberRange{//immutable class
private static class IntPair{
final int lower;
final int upper;
public IntPair(final int l,final int u){
this.lower = l;
this.upper = u;
}
}
//atomic
private final AtomicReference<IntPair> values = new AtomicReference<>(new IntPair(0,0));
public int getLower(){return values.get().lower;}
public int getUpper(){return values.get().upper;}
public void setLower(int i){
while(true){
IntPair old = values.get();
if(i > old.upper){
throw new RuntimeException("argument is too up");
}else{
IntPair newPair = new IntPair(i,old.upper);
if(values.compareAndSet(old, newPair)){
return;
}
}
}
}
public void setUpper(int i){
while(true){
IntPair old = values.get();
if(i < old.lower){
//throw new RuntimeException("argument is too low");
}else{
IntPair newPair = new IntPair(old.lower,i);
if(values.compareAndSet(old, newPair)){
return;
}
}
}
}
}
public class Thread2_3 {
public static void main(String[] args) throws InterruptedException {
final CasNumberRange number = new CasNumberRange();
for( int i=0;i<1000;i++){
new Thread(new Runnable(){
@Override
public void run() {
number.setLower(number.getLower()+1);
number.setUpper(number.getUpper()+1);
}
}).start();
}
}
}
相关文章
- 暂无相关文章
用户点评