Queue与Deque的区别:
Queue单向队列,先进先出。
Deque 双向队列
ArrayBlockingQueue和LinkedBlockingQueue的区别:
1.ArrayBlockingQueue定长的缓冲队列;LinkedBlockingQueue 无界的缓冲队列。
2.队列中锁的实现不同:ArrayBlockingQueue实现的队列中的锁是没有分离的,即生产和消费用的是同一个锁;LinkedBlockingQueue实现的队列中的锁是分离的,即生产用的是putLock,消费是takeLock
3.在生产或消费时操作不同:ArrayBlockingQueue实现的队列中在生产和消费的时候,是直接将元素插入或移除的;LinkedBlockingQueue实现的队列中在生产和消费的时候,需要把元素转换为Node<E>进行插入或移除,会影响性能。
4.队列大小初始化方式不同:ArrayBlockingQueue实现的队列中必须指定队列的大小;LinkedBlockingQueue实现的队列中可以不指定队列的大小,默认是Integer.MAX_VALUE
2、在使用ArrayBlockingQueue和LinkedBlockingQueue分别对1000000个简单字符做入队操作时,LinkedBlockingQueue的消耗是ArrayBlockingQueue消耗的10倍左右,
即LinkedBlockingQueue消耗在1500毫秒左右,ArrayBlockingQueue只需150毫秒左右。
简单示例:
Queue单向队列,先进先出。
Deque 双向队列
ArrayBlockingQueue和LinkedBlockingQueue的区别:
1.ArrayBlockingQueue定长的缓冲队列;LinkedBlockingQueue 无界的缓冲队列。
2.队列中锁的实现不同:ArrayBlockingQueue实现的队列中的锁是没有分离的,即生产和消费用的是同一个锁;LinkedBlockingQueue实现的队列中的锁是分离的,即生产用的是putLock,消费是takeLock
3.在生产或消费时操作不同:ArrayBlockingQueue实现的队列中在生产和消费的时候,是直接将元素插入或移除的;LinkedBlockingQueue实现的队列中在生产和消费的时候,需要把元素转换为Node<E>进行插入或移除,会影响性能。
4.队列大小初始化方式不同:ArrayBlockingQueue实现的队列中必须指定队列的大小;LinkedBlockingQueue实现的队列中可以不指定队列的大小,默认是Integer.MAX_VALUE
注意:
1、在使用LinkedBlockingQueue时,若用默认大小且当生产速度大于消费速度时候,有可能会内存溢出。2、在使用ArrayBlockingQueue和LinkedBlockingQueue分别对1000000个简单字符做入队操作时,LinkedBlockingQueue的消耗是ArrayBlockingQueue消耗的10倍左右,
即LinkedBlockingQueue消耗在1500毫秒左右,ArrayBlockingQueue只需150毫秒左右。
简单示例:
BlockingQueue<String> queue = new LinkedBlockingQueue<>(2);
boolean addOK = queue.add("a");// will throw IllegalStateException when Queue is full
try {
queue.put("b");// will blocking when Queue is full
addOK = queue.offer("c");// will not blocking when Queue is full
System.out.println(addOK);
addOK = queue.offer("d", 1, TimeUnit.SECONDS);//will blocking the times when Queue is full
System.out.println(addOK);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(queue);
try {
String value = queue.take(); // will blocking when Queue is empty
value = queue.poll();//// will not blocking when Queue is empty, return null if empty
value = queue.poll(1, TimeUnit.SECONDS);//will blocking the times when Queue is empty, return null if empty
queue.peek();//Retrieves, but does not remove, the head of this queue,null if this queue is empty
} catch (InterruptedException e) {
e.printStackTrace();
}