为什么这个具有两个堆栈的队列的实现是不可变的且线程安全的?
我见过这种使用两个堆栈实现队列的方法: https://stackoverflow.com/a/2050402/494094
我读到,这样队列是不可变的且线程安全的。将其与普通队列分开并使其不可变且线程安全有什么意义?
如果有人能以简单、非专业的方式解释它,我将非常感激。
I've seen this way of implementing a queue with two stacks: https://stackoverflow.com/a/2050402/494094
And I've read that this way the queue is immutable and thread-safe. What's the point that separates this from a normal queue and makes it immutable and thread-safe?
I'd really appreciate it if someone could explain it in a simple, non-professional way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如何使用两个堆栈实现队列?解释了更多和有一些代码。
如果您以低级方式执行此操作,您将拥有两个内存区域和两个指针
一个指针在写入时递增,另一个指针在读取时递增。
一旦读取区域用完,就反转写入区域并交换两者。
因此,阅读不会干扰写作,反之亦然。两个操作之间唯一的联系是在“反向和交换”操作期间,然后每个人都必须等待。
How to implement a queue using two stacks? explains more and has some code.
If you do this in a low-level way you will have two memory areas and two pointers
One pointer increments when you write, the other when you read
Once the read area is used up, you reverse the write area and swap the two.
So there is no chance of the reading interfering with the writing and vice versa. The only connection between the two operations is during the "reverse and swap" operation, and then everybody has to wait.