ArrayBlockingQueue、LinkedBlockingQueue
区别:一个一把锁,一个两把锁。
ArrayBlockingQueue用Condition写
public class ProviderConsumer<T> {
private int length;
private Queue<T> queue;
private ReentrantLock lock = new ReentrantLock();
private Condition provideCondition = lock.newCondition();
private Condition consumeCondition = lock.newCondition();
public ProviderConsumer(int length){
this.length = length;
this.queue = new LinkedList<T>();
}
public void provide(T product){
lock.lock();
try {
while (queue.size() >= length) {
provideCondition.await();
}
queue.add(product);
consumeCondition.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public T consume() {
lock.lock();
try {
while (queue.isEmpty()) {
consumeCondition.await();
}
T product = queue.remove();
provideCondition.signal();
return product;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return null;
}
}