问题
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.
回答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.
来源:https://stackoverflow.com/questions/8357459/why-is-this-implementation-of-a-queue-with-two-stacks-immutable-and-thread-safe