最近我遇到了这个问题:有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。
我有以下问题:
上述实施中是否有任何问题?
实现无锁消费者队列的其他方法有哪些?