java - LinkedBlockingQueue 使用非线程安全列表

标签 java multithreading concurrency thread-safety blockingqueue

我想知道为什么不 LinkedBlockingQueue如果我们将底层数据结构更改为像 java.util.LinkedList 这样的非线程安全列表,是否可以工作?当我尝试时,我得到一个 NoSuchElementException 。它不是由锁(takeLock)保护的,这使得它是线程安全的吗?

private final List<E> list;
private final ReentrantLock takeLock;
private final ReentrantLock putLock;
private final Condition     notFull;
private final Condition     notEmpty;
private final AtomicInteger count;

public LinkedBlockingQueue() {
    takeLock = new ReentrantLock();
    putLock = new ReentrantLock();
    notFull = putLock.newCondition();
    notEmpty = takeLock.newCondition();
    count = new AtomicInteger(0);
    list = new LinkedList<E>();
}

public E get() {
   E item = null;
   int c = -1;
   try {
      takeLock.lockInterruptibly();
      while (count.get() == 0) notEmpty.await();

      // original -> item = dequeue();
      item = list.remove();   // NoSuchElementException

      c = count.getAndDecrement();
   } 
   catch (InterruptedException ie) {} 
   finally {
      takeLock.unlock();
   }

   if (c == capacity) signalNotFull();
   return item;
}

public void put(E e) {
   int c = -1;
   try {
      putLock.lockInterruptibly();
      while (count.get() == BOUND_SIZE) notFull.await();

      // original -> enqueue(node);
      list.add(e);

      c = count.getAndIncrement();
   } 
   catch (InterruptedException ie) {} 
   finally {
      putLock.unlock();
   }

   if (c == 0) signalNotEmpty();
}

最佳答案

您正在使用两个单独的锁定对象:

takeLock = new ReentrantLock();
putLock = new ReentrantLock();
notFull = putLock.newCondition();
notEmpty = takeLock.newCondition();

这是错误的。首先,您必须对 put 和 take 操作使用相同的锁对象。此外,您必须使用相同的锁定对象创建条件。

lock = new ReentrantLock();
notFull = lock.newCondition();
notEmpty = lock.newCondition();

并且您应该使用给定的锁引用替换 takeLock 和 putLock 用法。

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html

关于java - LinkedBlockingQueue 使用非线程安全列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28655511/

相关文章:

java - 需要有关 Java 设计模式的帮助

java - 解析 Gif 图像正在降低质量和堆叠帧

java - Executor 创建的线程池会释放内存吗?

c++ - PostThreadMessage 到另一个进程

c++ - QtCore、QMutex类、锁函数——栈溢出失败

选择更新甚至排序之间的 PostgreSQL 死锁

Java线程加入后卡住

java - swingworkers 的背景任务变得连续

java - 我如何使用java写入文本文件?

java - Jersey REST 中的 InputStream 只返回一个字节