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();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值