两者都是常用的有界阻塞队列,不同点如下:
1、ArrayBlockingQueue是数组结构的(final Object[] items;),LinkedBlockingQueue是链表结构的(private transient Node<E> head;)。
2、ArrayBlockingQueue直接保存对象,LinkedBlockingQueue需要把对象转为Node类型再保存。
3、ArrayBlockingQueue读写共用一把锁,不能做到同时(任意时刻)读写,宏观上看是读写交替进行的:
/** Main lock guarding all access */
final ReentrantLock lock;
/** Condition for waiting takes */
private final Condition notEmpty;
/** Condition for waiting puts */
private final Condition notFull;
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
LinkedBlockingQueue读写锁是分离的,只要链表不空或没有达到容量上限就能同时读写:
private final ReentrantLock takeLock = new ReentrantLock();
/** Wait queue for waiting takes */
private final Condition notEmpty = takeLock.newCondition();
/** Lock held by put, offer, etc */
private final ReentrantLock putLock = new ReentrantLock();
/** Wait queue for waiting puts */
private final Condition notFull = putLock.newCondition();
4、ArrayBlockingQueue使用时必须指定容量,LinkedBlockingQueue可以不指定容量,此时容量为Integer.MAX_VALUE