Java - LinkedBlockingQueue问题
1 LinkedBlockingQueue queJobs = new LinkedBlockingQueue(150); 2 .......... 3 .. Some other code.... 4 .......... 5 Job curJob = queJobs.take(); 6 .................... 7 .. Again some other code... 8 .................... 9 if(condition1){ 10 queJobs.put(curJob); 11 }
我的问题是当条件1为真时,我将对象放回到队列中。但最初它位于队列的顶部,但是放入后,它将位于队列的末尾。
我的要求是:
1.我可以将元素放回队列顶部
或
2. 不知何故,我可以在第 5 行等待,而不从队列中删除元素。
1 LinkedBlockingQueue queJobs = new LinkedBlockingQueue(150); 2 .......... 3 .. Some other code.... 4 .......... 5 Job curJob = queJobs.take(); 6 .................... 7 .. Again some other code... 8 .................... 9 if(condition1){ 10 queJobs.put(curJob); 11 }
my problem is when condition1 is true, I am putting back the object into queue. but initially it was on top of the queue, but after putting, it will go at the end of queue.
My requirement is :
1. I can put back the element on top of the queue
or
2. Somehow I can wait at line 5, without removing element from the queue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
队列被定义为在一端读取并在另一端写入。所以不,不能把它放回去。
但是您可以使用 LinkedBlockingDeque 代替,在这方面更加通用。
如果这不是一个选项,您可以使用 peek() 获取但不删除
curJob
,稍后仅删除它if (!condition1)
。更新
那么 peek() 肯定不适合你。但我怀疑你的整体逻辑有缺陷。通常您不必将作业放回队列中。也许更好的解决方案是使用另一个只有工作线程知道的集合,您将启动但尚未完成的作业放在其中,并在作业队列之前从该集合中读取。
A Queue is defined to be read at one end and written to at the other end. So no, can't put it back in.
But you can use a LinkedBlockingDeque instead, which is more versatile in this regard.
If this is not an option, you can use peek() to get, but not remove, the
curJob
and later only remove itif (!condition1)
.UPDATE
peek() will certainly not work for you then. But I suspect a shortcoming in your overall logic then. Normally you shouldn't have to put jobs back in the queue. Maybe the better solution is to use another collection which is only known to the worker thread, where you put the jobs that you started but not yet finished, and you read from that collection before the job queue.
您可以使用 peek() 来检索头部但不删除它。然后检查条件1是否为假。如果是,则使用 take() 将其删除。
可以将元素添加回头部,但很混乱。可以调用toArray().toList(),它支持在索引0处添加。
参考:http://download.oracle.com/javase/6/docs/api/java/util/concurrent/LinkedBlockingQueue.html
You can use peek() which retrieves the head but does not remove it. Then later check whether condition1 is false. If yes, then remove it with take().
It is possible to add the element back to the head but it is messy. You can call toArray().toList() which supports adding at index 0.
Reference: http://download.oracle.com/javase/6/docs/api/java/util/concurrent/LinkedBlockingQueue.html
更自然的选择可能是使用 PriorityBlockingQueue,它允许您为元素分配优先级。这并不完全是您所要求的,而只是一个建议。
A more natural fit might be to use a PriorityBlockingQueue that would allow you to assign priorities to the elements. This is not exactly what you asked for, but is just a suggestion.