Java BlockingQueue take() vs poll() [英] Java BlockingQueue take() vs poll()

查看:26
本文介绍了Java BlockingQueue take() vs poll()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在无限循环中使用队列中的值时 - 什么会更有效:

When consuming values from a Queue in an infinite loop -- what would be more efficient:

1) 在队列上阻塞,直到通过 take() 获得一个值

1) Blocking on the Queue until a value is available via take()

while (value = queue.take()) { doSomething(value); }

2) 休眠 n 毫秒并检查物品是否可用

2) Sleeping for n milliseconds and checking if an item is available

while (true) {

    if ((value = queue.poll()) != null) { doSomething(value); }

    Thread.sleep(1000);
}

推荐答案

阻塞可能更有效.在后台,如果没有可用的元素,最初调用 take() 的线程会进入睡眠状态,让其他线程做他们需要做的任何事情.将元素添加到队列的方法将在添加元素时唤醒等待线程,因此只需最少的时间一遍又一遍地检查队列以确定元素是否可用.

Blocking is likely more efficient. In the background, the thread that initially calls take() goes to sleep if there is no element available, letting other threads do whatever they need to do. The methods that add elements to the Queue will then wake up waiting threads when an element is added, so minimal time is spent checking the queue over and over again for whether an element is available.

这篇关于Java BlockingQueue take() vs poll()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆