无锁队列java实现,java - 实现多用户无锁队列 - SO中文参考 - www.soinside.com

最近我遇到了这个问题:有3个消费者线程需要实现一个无锁队列(不能使用同步),这样就不会阻塞消费线程。假设队列已包含数据。

我想了一会儿,遇到了原子操作,如果仔细使用可以提供帮助。我的实现如下所示。由于数据已经在队列中,我没有实现enqueue方法并在构造函数中填充数组。

public class SPMCQueue {

private AtomicInteger index = new AtomicInteger(0);

public int[] arr;

public SPMCQueue(int size) {

arr = IntStream.range(0, size).toArray();

}

public Integer dequeue() {

Integer ret = null;

int x = index.getAndIncrement();

if (x < arr.length) {

ret = arr[x];

System.out.println(arr[x] + " by " + Thread.currentThread().getName());

}

else {

throw new RuntimeException("Queue is empty");

}

return ret;

}

}

class QueueTest {

public static void main(String[] args) {

SPMCQueueq = new SPMCQueue(40);

Runnable t1 = () -> {

try {

while (true) {

q.dequeue();

}

}catch(Exception e) {

}

};

Runnable t2 = () -> {

try {

while(true) { q.dequeue(); }

}catch(Exception e) {

}

};

Runnable r3 = () -> {

try {

while(true) { q.dequeue(); }

} catch (Exception e) {

// TODO Auto-generated catch block

//e.printStackTrace();

}

};

Thread thread1 = new Thread(t1);

Thread thread2 = new Thread(t2);

Thread thread3 = new Thread(r3);

thread1.start();

thread2.start();

thread3.start();

}

}

我已经执行了上面的程序,结果显示所有3个消费者都在消耗数据,虽然乱序,有些线程消耗的数据比其他线程多,但我没有看到任何数据在o中多次出现/ p。

我有以下问题:

上述实施中是否有任何问题?

实现无锁消费者队列的其他方法有哪些?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值