【问题标题】:Adding elements from two threads to the same ConcurrentLinkedQueue at the same time同时将两个线程中的元素添加到同一个 ConcurrentLinkedQueue
【发布时间】:2015-12-28 17:06:16
【问题描述】:

假设线程 A 尝试将一个元素添加到 ConcurrentLinkedQueue,同时线程 B 尝试将不同的元素添加到同一个 ConcurrentLinkedQueue。

这两个项目是否会被添加到队列中,或者我会遇到并发问题(比如说,可能只会插入一个)?
我知道这个队列是线程安全的,但是我不知道这是否意味着当我从不同的线程同时调用它两次时我可以假设这个方法也是安全的。

如果不是,那么 put/offer 方法在这种情况下可能是安全的吗?

【问题讨论】:

  • Concurrent 类的整体理念是它们是线程安全且高效的。
  • ...“线程安全”类的整体理念是,无论有多少来自不同线程的同时调用,它的所有方法都做“正确的事情”。并发程序中“正确的事情”的含义并不总是 100% 显而易见,但在队列的情况下,这至少意味着添加的元素不会简单地从队列中消失,而且你永远不会从队列中拉出一个未添加的元素。

标签: java multithreading concurrency


【解决方案1】:

您可以安全地同时从不同线程向ConcurrentLinkedQueue 添加元素。所有元素都将在队列中。如果每个线程从两个线程调用add() 方法一次,那么队列中将有两个元素。 ConcurrentLinkedQueue的接口中没有方法put()。方法add() 的作用与offer() 相同。你可以在源码中看到这个

/**
 * Inserts the specified element at the tail of this queue.
 * As the queue is unbounded, this method will never throw
 * {@link IllegalStateException} or return {@code false}.
 *
 * @return {@code true} (as specified by {@link Collection#add})
 * @throws NullPointerException if the specified element is null
 */
public boolean add(E e) {
    return offer(e);
}

【讨论】:

  • tnx.它是否适用于队列的所有添加方法? (添加和提供方法)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-20
相关资源
最近更新 更多