gpt4 book ai didi

没有同步的Java等待/通知实现

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:33:25 24 4
gpt4 key购买 nike

我有一个包含数十个生产者和一个消费者的场景。时间很关键:出于性能原因,我想避免对生产者进行任何锁定,并且我希望消费者在没有消息准备就绪时尽可能少地等待。

我已经开始使用 ConcurrentLinkedQueue,但我不喜欢在 queue.poll() == null 时对消费者调用 sleep,因为我可能会浪费宝贵的毫秒,我不想使用 yield,因为我最终会浪费 cpu。

所以我开始实现一种 ConcurrentBlockingQueue 以便消费者可以运行类似的东西:

T item = queue.poll();
if(item == null) {
wait();
item = queue.poll();
}
return item;

制作人是这样的:

queue.offer(item);
notify();

不幸的是,等待/通知只适用于同步块(synchronized block),这反过来会大大降低生产者的性能。 是否有其他不需要同步的等待/通知机制的实现?

我知道与等待和通知不同步相关的风险,我设法通过让外部线程运行以下命令来解决这些风险:

while(true) {
notify();
sleep(100);
}

最佳答案

I've started using a ConcurrentLinkedQueue, but I don't like to call sleep on the consumer when queue.poll() == null

你应该检查the BlockingQueue interface ,它有一个 take 方法,该方法会阻塞直到项目可用。

它有多个实现,如 javadoc 中所述,但 ConcurrentLinkedQueue 不是其中之一:

All Known Implementing Classes:
ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, LinkedTransferQueue, PriorityBlockingQueue, SynchronousQueue

关于没有同步的Java等待/通知实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48803979/

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