0

首先,我使用搜索并找到了与此问题相关的 n 个主题。不幸的是,他们没有帮助我,所以这将是 n++ 主题:)

情况:我将有很少的工作线程(同一个类,只有很多重复项)(我们称它们为 WT)和一个结果写入线程(RT)。

WT 会将对象添加到队列中,而 RT 将获取它们。由于会有很多 WT 不会有任何内存问题(独立于最大队列大小)?这些操作会互相等待完成吗?

此外,据我所知, BlockingQueue 很慢,所以也许我应该离开它并在同步块中使用普通队列?或者我应该通过使用 SynchronizedQueue 来考虑我自己?

4

1 回答 1

2

LinkedBlockingQueue is designed to handle multiple threads writing to the same queue. From the documentation:

BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation.

Therefore, you are quite safe (unless you expect the bulk operations to be atomic).

Of course, if thread A and thread B are writing to the same queue, the order of A's items relative to B's items will be indeterminate unless you synchronize A and B.

As to the choice of queue implementation, go with the simplest that does the job, and then profile. This will give you accurate data on where the bottlenecks are so you won't have to guess.

于 2013-03-08T13:56:13.603 回答