在java生产者消费者专题---谈谈优化(一)中说明了当知足唤醒条件时须要使用notifyAll而不是notify,可是notifyAll依然存在效率上的问题,由于notifyAll唤醒的是全部线程,因为生产者线程会在队列满的时候进入等待、消费者线程会在队列为空的时候进入等待,所以生产者须要唤醒的条件就是队列满了、消费者须要唤醒的条件就是队列空了,不能像原来同样不加检测条件直接唤醒,因而程序优化以下:java
package pro_con;优化
import java.util.LinkedList;this
public class QueueWithWait2<T> extends BlockingQueue<T> {
private LinkedList<T> queue = new LinkedList<>();
private final int cacheSize;.net
public QueueWithWait2(int cacheSize) {
super();
this.cacheSize = cacheSize;
}线程
public T take() {
synchronized (queue) {
while(true) {
if(queue.size()>0) {
boolean full = queue.size() == cacheSize;
T obj = queue.poll();
if(full) {
queue.notifyAll();
}
return obj;
}else {
try {
queue.wait();
} catch (InterruptedException e) {
}
}
}
}
}blog
public void put(T obj) {队列
synchronized (queue) {
while (true) {
if (queue.size() < cacheSize) {
boolean empty=queue.size()==0;
queue.offer(obj);
if(empty) {
queue.notifyAll();
}
break;
} else {
try {
queue.wait();
} catch (InterruptedException e) {
}
}get
}
}it
}io
}
改进后平均每秒消费消息65541个比原先每秒消费个数63523稍微快点。
注意这里的notifyAll还不能换成notify由于还会发生相似 java生产者消费者专题---谈谈优化(一)中的死锁状况,其实这里也并无真正达到按需唤醒的目标,会在下一篇进行分析。