之所以能保证线程安全是因为两点:
1,private final AtomicInteger count = new AtomicInteger(); 保证了 存的数量和取得数量的安全性
2,初始化的时候 last = head = new Node(null);
下面详细说一下为什么:
首先线程不安全是因为多个线程操作了一个共享变量导致。
当count =0的时候 head = new Node(null);
①先说put
当调用put的时候,由于加了ReentrantLock 锁
从而保证了put方法的线程安全性
put采用的是尾差法,head 是一个值为空的Node节点
public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
// Note: convention in all put/take/etc is to preset local var
// holding count negative to indicate failure unless set.
int c = -1;
Node<E> node = new Node<E>(e);
final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count;
putLock.lockInterruptibly();
try {
/*
* Note that count is used in wait guard even though it is
* not protected by lock. This works because count can
* only decrease at this point (all other puts are shut
* out by lock), and we (or some other waiting put) are
* signalled if it ever changes from capacity. Similarly
* for all other uses of count in other wait guards.
*/
while (count.get() == capacity) {
notFull.await();
}
enqueue(node);
c = count.getAndIncrement();
if (c + 1 < capacity)
notFull.signal();
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
}
private void enqueue(Node<E> node) {
// assert putLock.isHeldByCurrentThread();
// assert last.next == null;
last = last.next = node;
}
②再说take
也是加了ReentrantLock锁保证了take的线程安全性
当count≠0的时候 调用dequeue 取数的时候会将head节点的next节点的item=null
并且将next置为head节点
当count=0的时候会调用notEmpty.await()进入条件等待队列进行阻塞
此时head节点是值为null的Node节点
假设现在有线程调用put,会在这个head节点继续往后添加,
也就是说此时的值为null的Node节点 会成为take和put的临界点,有可能成为同时被take和put获取到
节点,而tput是操作的node节点的next的值,take取的是node节点的item。
所以说虽然是两把锁 但是 count 和 head = new Node(null); 保证了线程的安全性
public E take() throws InterruptedException {
E x;
int c = -1;
final AtomicInteger count = this.count;
final ReentrantLock takeLock = this.takeLock;
takeLock.lockInterruptibly();
try {
while (count.get() == 0) {
notEmpty.await();
}
x = dequeue();
c = count.getAndDecrement();
if (c > 1)
notEmpty.signal();
} finally {
takeLock.unlock();
}
if (c == capacity)
signalNotFull();
return x;
}
private E dequeue() {
// assert takeLock.isHeldByCurrentThread();
// assert head.item == null;
Node<E> h = head;
Node<E> first = h.next;
h.next = h; // help GC
head = first;
E x = first.item;
first.item = null;
return x;
}