兑现一个简单的阻塞队列(2)
实现一个简单的阻塞队列(2)
classBlockingQ{
privateObject notEmpty= newObject();
privateObject notFull= newObject();
privateQueue<Object> linkedList= newLinkedList<Object>();
privateintmaxLength= 10;
publicObject take() throwsInterruptedException{
synchronized(notEmpty) {
if(linkedList.size() == 0) {
notEmpty.wait();
}
synchronized(notFull) {分别需要对notEmpty和notFull加锁
if(linkedList.size() == maxLength) {
notFull.notifyAll();
}
returnlinkedList.poll();
}
}
}
publicvoidoffer(Object object) throwsInterruptedException{
synchronized(notEmpty) {分别需要对notEmpty和notFull加锁
if(linkedList.size() == 0) {
notEmpty.notifyAll();
}
synchronized(notFull) {
if(linkedList.size() == maxLength) {
notFull.wait();
}
linkedList.add(object);
}
}
}
}
通过实现简单的阻塞队列来学习并发知识
classBlockingQ{
privateObject notEmpty= newObject();
privateObject notFull= newObject();
privateQueue<Object> linkedList= newLinkedList<Object>();
privateintmaxLength= 10;
publicObject take() throwsInterruptedException{
synchronized(notEmpty) {
if(linkedList.size() == 0) {
notEmpty.wait();
}
synchronized(notFull) {分别需要对notEmpty和notFull加锁
if(linkedList.size() == maxLength) {
notFull.notifyAll();
}
returnlinkedList.poll();
}
}
}
publicvoidoffer(Object object) throwsInterruptedException{
synchronized(notEmpty) {分别需要对notEmpty和notFull加锁
if(linkedList.size() == 0) {
notEmpty.notifyAll();
}
synchronized(notFull) {
if(linkedList.size() == maxLength) {
notFull.wait();
}
linkedList.add(object);
}
}
}
}
通过实现简单的阻塞队列来学习并发知识