/**
* 使用BlockingQueue的时候,尽量不要使用从Queue继承下来的 方法,否则就失去了Blocking的特性了
*
* @author xingliangbo
* @version $Id: BlockQueue.java, v 0.1 2015年11月4日 下午9:55:26 xingliangbo Exp $
*/
public class BlockQueue {
private Object lock = new Object();
private Queue<Object> links = Lists.newLinkedList();
public Object take() throws InterruptedException {
// 执行wait之前必须先获取到锁 执行完后会释放 这边面试会问到哦 哈哈
synchronized (lock) {
if (links.size() == 0) {
lock.wait();
}
return links.poll();
}
}
public void offer(Object obj) {
synchronized (lock) {
//执行notifyAll 也必须先获取锁
if (links.size() == 0) {
lock.notifyAll();
}
links.add(obj);
}
}
/**
* 类似多生产者多消费者 缓冲池
*
* @author xingliangbo
* @version $Id: BlockQueue2.java, v 0.1 2015年11月4日 下午10:01:15 xingliangbo Exp $
*/
public class BlockQueue2 {
private Object emptyLock = new Object();
private Object fullLock = new Object();
private Queue<Object> links = Lists.newLinkedList();
private int maxLength = 100;
public Object take() throws InterruptedException {
synchronized (emptyLock) {
if (links.size() == 0) {
//等待生产者生产
emptyLock.wait();
}
synchronized (fullLock) {
if (links.size() == maxLength) {
//生产者 你可以生产了
fullLock.notifyAll();
}
return links.poll();
}
}
}
public void offer(Object obj) throws InterruptedException {
synchronized (emptyLock) {
if (links.size() == 0) {
//消费者 你可以消费了
emptyLock.notifyAll();
}
synchronized (fullLock) {
//消费者 你快来消费了
if (links.size() == maxLength) {
fullLock.wait();
}
links.add(obj);
}
}
}
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.google.common.collect.Lists;
/**
* Synchronized 是lock的简单实现,Synchronized 把lock 和condition合并了,而且只有一个condition
*
* @author xingliangbo
* @version $Id: BlockQueue3.java, v 0.1 2015年11月4日 下午10:16:57 xingliangbo Exp $
*/
public class BlockQueue3 {
private Lock lock = new ReentrantLock();
private Condition empty = lock.newCondition();
private Condition full = lock.newCondition();
private Queue<Object> links = Lists.newLinkedList();
private int maxLength = 100;
public Object take() {
lock.lock();
try {
if (links.size() == 0) {
empty.await();
}
if (links.size() == maxLength) {
full.signalAll();
}
return links.poll();
} catch (Exception e) {
} finally {
lock.unlock();
}
return null;
}
public void offer(Object obj) {
lock.lock();
try {
if (links.size() == 0) {
empty.signalAll();
}
if (links.size() == maxLength) {
full.await();
}
links.add(obj);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
转载于:https://my.oschina.net/xliangbo/blog/526013