java取消队列_如何使用循环从Java中删除队列中的元素

您可以在队列中完成所有元素,直到队列中的所有元素为止,然后才能使用

poll和p̶u̶s̶h̶

offer.这是一个例子:

Mail firstMail = mailbox.peek();

Mail currentMail = mailbox.pop();

while (true) {

//a base condition to stop the loop

Mail tempMail = mailbox.peek();

if (tempMail == null || tempMail.equals(firstMail)) {

mailbox.offer(currentMail);

break;

}

//if there's nothing wrong with the current mail, then re add to mailbox

if (!badNews(currentMail)) {

mailbox.offer(currentMail);

}

currentMail = mailbox.poll();

}

请注意,只有在单个线程中执行此代码并且没有其他线程从此队列中删除项目时,此方法才有效.

也许您需要检查是否真的要轮询或从BlockingQueue中获取元素.提供和放置类似.

更多信息:

另一种不那么错误的方法是使用临时集合,不一定是并发的,并将您仍需要的元素存储在队列中.这是一个启动示例:

List mailListTemp = new ArrayList<>();

while (mailbox.peek() != null) {

Mail mail = mailbox.take();

if (!badNews(mail)) {

mailListTemp.add(mail);

}

}

for (Mail mail : mailListTemp) {

mailbox.offer(mail);

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值