慕村9548890
如果您要获取最高优先级的消息,则可以在内存中或从数据库中创建一个简单的优先级队列。但是您打算从所有队列中获取一些消息。这是一个粗略的实现,可以给您一个想法。您可以将其推断为批量方案。import java.util.ArrayList;import java.util.Deque;import java.util.LinkedList;import java.util.List;import java.util.Optional;public final class NQueue{ private final List<Deque<String>> queues = new ArrayList<>(); private final int[] poll; private int currentIndex; private int queueIndex; private final int pollWidth; public NQueue(int[] poll) { this.poll = new int[poll.length]; int sum = 0; for (int i = 0; i < poll.length; i++) { int val = poll[i]; sum += val; this.poll[i] = sum; queues.add(new LinkedList<>()); } this.pollWidth = sum; } public synchronized void addMessage(String msg, int priority) { queues.get(priority).add(msg); } public synchronized Optional<String> removeMessage() { for (int i = 0; i < this.pollWidth; i++) { updateQueueIndex(); String msg = queues.get(queueIndex).poll(); currentIndex++; if (msg != null) { return Optional.of(msg); } } return Optional.empty(); } private void updateQueueIndex() { if (currentIndex == pollWidth) { currentIndex = 0; queueIndex = 0; } else if (currentIndex == this.poll[this.queueIndex]) { queueIndex++; } }}样本客户端。//in every run, poll 3 from priority 0, 2 from priority 1 and 1 from priority 2NQueue nQueue = new NQueue(new int[]{3,2,1});nQueue.addMessage("a",0);nQueue.addMessage("b",1);nQueue.addMessage("c",2);nQueue.addMessage("d",1);nQueue.addMessage("e",0);nQueue.addMessage("f",1);nQueue.addMessage("g",1);for (int i = 0; i < 10; i++){ Optional<String> s = nQueue.removeMessage(); System.out.println("s = " + s);}它打印s = Optional[a]s = Optional[e]s = Optional[b]s = Optional[d]s = Optional[c]s = Optional[f]s = Optional[g]s = Optional.emptys = Optional.emptys = Optional.empty