代码
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.IntUnaryOperator;
public class Sequence {
private AtomicInteger value = new AtomicInteger();
private int s[]={2,1,4,5,6};
AtomicIntegerArray a = new AtomicIntegerArray(s);
AtomicReference<User> user = new AtomicReference<User>();
AtomicIntegerFieldUpdater<User> old = AtomicIntegerFieldUpdater.newUpdater(User.class, "old");
/*
* public final int getAndUpdate(IntUnaryOperator updateFunction) {
int prev, next;
do {
prev = get();
next = updateFunction.applyAsInt(prev);
} while (!compareAndSet(prev, next));
return prev;
}底层采用cas操作,获取当前值和预期的下个值,cas比较,为真则返回
*
*/
public int getNext(){
return value.getAndIncrement();
}
public void getArrayNexy(){
old.getAndIncrement(new User());
// 数组第二个位置的元素加10
a.addAndGet(1, 10);
a.getAndIncrement(1);
}
public static void main(String[] args) {
Sequence s = new Sequence();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
System.out.println(Thread.currentThread().getName() + " "+s.getNext());
try {
Thread.sleep(100);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
System.out.println(Thread.currentThread().getName() + " "+s.getNext());
try {
Thread.sleep(100);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
}
}
网友评论