Java无锁队列的问题

圣诞老人123 2018-03-25 10:15:27
题目是实现一个无锁的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还会打印负数 求教
...全文
450 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复

67,549

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧