Java无锁队列的问题
题目是实现一个无锁的Stack,并写一段测试代码(多线程访问),证明这个Stack是线程安全的。
public class TestCAS {
static LockFreeStack<Object> stack = new LockFreeStack<>();
static class Node<T> {
private T v;
private Node<T> next;
public Node(T value, Node<T> next){
v = value; this.next = next;
}
public void setNext(Node<T> next){
this.next = next;
}
public Node<T> getNext(){
return next;
}
public void setValue(T v){
this.v = v;
}
public T getValue(){
return v;
}
}
static class LockFreeStack<T>{
AtomicStampedReference<Node<T>> top = new AtomicStampedReference<>(null,0);
AtomicLong count = new AtomicLong(0);
public void push(T value){
Node<T> newvalue = new Node(value,null);
Node<T> oldvalue = null;
int stamp = 0;
do {
stamp = top.getStamp();
oldvalue = top.getReference();
newvalue.setNext(oldvalue);
} while(!top.compareAndSet(oldvalue,newvalue,stamp,stamp+1));
count.incrementAndGet();
System.out.println("count2:" + count.get());
}
public T pop(){
Node<T> newvalue = null;
Node<T> oldvalue = null;
int stamp = 0;
do {
stamp = top.getStamp();
oldvalue = top.getReference();
if(null == oldvalue){
continue;
}
newvalue = oldvalue.getNext();
} while(null == oldvalue || !top.compareAndSet(oldvalue,newvalue,stamp,stamp+1));
count.decrementAndGet();
System.out.println("count:"+count.get());
return oldvalue.getValue();
}
public void getCount(){
System.out.println("All:"+count.get());
}
}
static class Push extends Thread {
@Override
public void run() {
for(;;) {
stack.push("Random->"+Math.random());
Thread.yield();
}
}
}
static class Pop extends Thread {
@Override
public void run() {
for(;;) {
stack.pop();
Thread.yield();
//System.out.println("已出栈:" + stack.pop());
}
}
}
public static void main(String[] args) throws InterruptedException {
Push [] pushs = new Push[10];
Pop [] pop = new Pop[10];
for(int i = 0; i < 10; i++) {
pushs[i] = new Push();
pop[i] = new Pop();
}
for(int i = 0; i < 10; i++) {
pushs[i].start();
pop[i].start();
}
for (;;){
Thread.sleep(1000);
stack.getCount();
}
}
}
为什么count还会打印负数 求教