gpt4 book ai didi

java - 轮询是否会阻塞 LinkedBlockingQueue 中的其他操作?

转载 作者:行者123 更新时间:2023-12-02 13:15:29 27 4
gpt4 key购买 nike

在下面的伪代码中,我有一个 poll() 函数,该函数在主线程中永远被调用。当我在 poll() 中没有使用 sleep() 语句时,每分钟只有 2-3 个项目被另一个线程添加到队列中。这是否意味着轮询会阻塞 put() 语句?

如何解决这个问题?

public class Test extends Thread{
private LinkedBlockingQueue<Object> queue = null;

Test(){
queue = new LinkedBlockingQueue<Object>(10);
}

public void run(){
// Do stuff, get incoming object from network
queue.put(o);
}

public Object poll(){
Object o = queue.poll();
sleep(1000);
return o;
}
}

最佳答案

Does this mean that polling blocks the put() statement?

不,LinkedBlockingQueue 是完全可重入的,并且 poll() 方法不会阻塞 put()。但是,poll() 方法会立即返回。您可能应该使用 queue.take() 来等待队列中出现项目,而不是在队列为空时返回 null。

// wait for there to be an object in the queue
Object o = queue.take();
// no sleep necessary
return o;

由于您正在构建一个包含 10 个条目的受限阻塞队列,我猜想 main 在 sleep() 上阻塞,然后队列就会填满并减慢您的程序。如果 poll() 返回 null 并 sleep 较短的时间,您可能应该只sleep

编辑: 正如 @JohnVint 在评论中提到的,另一种选择是使用 poll(long, TimeUnit) 方法,该方法将等待将项目添加到该时间段的队列,如果计时器到期则返回null。这是等待队列中的某些内容的更简洁的方式。

// wait for 1000ms for there to be an object in the queue
Object o = queue.poll(1000, TimeUnit.MILLISECONDS);
// no sleep necessary
return o;

关于java - 轮询是否会阻塞 LinkedBlockingQueue 中的其他操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10589445/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com