如何阻止方法put()和take()从’无限等待’中恢复?

huangapple go评论61阅读模式
英文:

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

使用BlockingQueueofferpoll方法。它们允许你为两种操作指定超时时间。

// 如果1秒后无法推送,返回false
blockingQueue.offer(5, 1, TimeUnit.SECONDS);

// 如果1秒后仍未收到项目,返回null
blockingQueue.poll(1, TimeUnit.SECONDS);

如果你不想使用超时,可以使用重载的方法,它们会立即返回相同的结果(offerpoll

// 如果无法推送,返回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.

huangapple
  • 本文由 发表于 2020年8月27日 04:42:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63605457.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定