英文:
How to stop methods put() and take() from 'endless waiting'?
问题
在BlockingQueue
的实现中,我们知道put()
和take()
方法具有阻塞的特性。
对于解决它们的无限等待状态,你有什么建议?例如,如果没有更多的项目可供读取,却调用了take()
。我的程序将会无限运行。你会如何解决这个问题?有什么提示吗?
英文:
In BlockingQueue
implementations we know that methods put()
and take()
have blocking nature.
What is your advice in solving their endless wait state? What if there are no more items to read and take()
is called for example. My program will run forever. How would you solve this? Any tips?
答案1
得分: 1
使用BlockingQueue
的offer
和poll
方法。它们允许你为两种操作指定超时时间。
// 如果1秒后无法推送,返回false
blockingQueue.offer(5, 1, TimeUnit.SECONDS);
// 如果1秒后仍未收到项目,返回null
blockingQueue.poll(1, TimeUnit.SECONDS);
如果你不想使用超时,可以使用重载的方法,它们会立即返回相同的结果(offer
,poll
)
// 如果无法推送,返回false
blockingQueue.offer(5);
// 如果未收到项目,返回null
blockingQueue.poll();
要小心检查poll
的返回值是否为null。根据项目的结构,你可能需要查阅Java的Optional
来帮助进行正确的null检查。
英文:
Use the offer
and poll
methods of the BLockingQueue
. They allow you to specify a timeout for both operations.
// returns false if it could not push after 1 second
blockingQueue.offer(5, 1, TimeUnit.SECONDS);
/// returns null if no item was received after 1 second
blockingQueue.poll(1, TimeUnit.SECONDS);
If you don't want a timeout you can use the overloaded methods which will return immediately with the same return behavior (offer
poll
)
// returns false if it could not push
blockingQueue.offer(5);
/// returns null if no item was received
blockingQueue.poll();
Be careful about checking if the return of poll
is null. Depending on the structure of the project, you might want to look into java Optional
to help with proper null checking.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论