简体   繁体   English

Java中的线程安全队列

[英]Thread safe queue in Java

I want to implement a queue, that is hit by multiple threads. 我想实现一个由多个线程命中的队列。

This is stack is in a singleton class. 这是堆栈的单例类。

Now, a simple solution is to synchronize this? 现在,一个简单的解决方案是同步这个? I assume it would need this as standard? 我认为它需要这个标准吗? However, I want to prioritize writing to it. 但是,我想优先写入它。

So, write is high priority, read is low priority. 因此,写入是高优先级,读取是低优先级。

Is this possible? 这可能吗?
Ideally writing by multiple threads without synchronizing would be great, if possible. 理想情况下,如果可能的话,多线程写入而不进行同步将是很好的。

Why do you want to avoid synchronizing? 为什么要避免同步? It's possible to write "lock-free" structures, but it's quite tricky and easy to get wrong. 可以编写“无锁”结构,但它非常棘手且容易出错。

If I were you, I'd use ArrayBlockingQueue or ConcurrentLinkedQueue (or one of the other structures from java.util.concurrent ) and make your life easy! 如果我是你,我会使用ArrayBlockingQueueConcurrentLinkedQueue (或java.util.concurrent中的其他结构之一),让你的生活变得轻松!

Oh, and I missed the bit about prioritising reads over writes. 哦,我错过了关于优先读取写入的一点。 You can do that with the ReentrantReadWriteLock class. 您可以使用ReentrantReadWriteLock类执行此操作。 Then you don't need a thread-safe queue - you just lock externally using the read-write lock depending on whether you're reading or writing. 然后你不需要一个线程安全的队列 - 你只需要使用读写锁在外部锁定,具体取决于你是在读还是写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM