对于生产者消费者模式来说,通常可以用java.util.concurrent包中的ArrayBlockingQueue来实现,但是有的时候不让用concurrent,必须自己手工实现。
编写生产者消费者有多种方式,一种是当条件不满足时就抛出异常,一种是通过轮询或休眠的方式,当条件不满足时进行循环,直到条件满足为止。但是还有更好的方式是,当条件不满足时可以让线程等待,如果是生产者产品过多,则让生产者等待,如果消费者消费过快,则消费者等待生产者生产。
1. 使用synchronized关键字来进行同步
这是一种最简单的实现方式,同时效率也比较高。
public class AbstractBoundedBuffer<V> {
private final V[] buf;
private int tail;
private int head;
private int count;
@SuppressWarnings("unchecked")
protected AbstractBoundedBuffer(int capacity) {
buf = (V[]) new Object[capacity];
head = 0;
tail = 0;
count = 0;
}
protected synchronized final void doPut(V v) {
buf[tail] = v;
if (++tail == buf.length) {
tail = 0;
}
++count;
}
protected synchronized final V doTake() {
V v = buf[head];
buf[head] = null;
if (++head == buf.length) {
head = 0;
}
--count;
return v;
}
protected synchronized boolean isFull() {
return count == buf.length;
}
protected synchronized boolean isEmpty() {
return count == 0;
}
}
public class BoundedBuffer<V> extends AbstractBoundedBuffer<V> {
public BoundedBuffer(int capacity) {
super(capacity);
}
public synchronized void put(V v) throws InterruptedException {
while (isFull())//等待并防止信号丢失
wait();
doPut(v);
notifyAll();//通知所有在当前对象上等待的对象
}
public synchronized V get() throws InterruptedException {
while (isEmpty())//等待并防止信号丢失
wait();
V v = doTake();
notifyAll();
return v;
}
}
public class BoundedBufferClient {
private static class Productor implements Runnable {
private BoundedBuffer<Integer> buf;
public Productor(BoundedBuffer<Integer> buf) {
this.buf = buf;
}
@Override
public void run() {
try {
int ss = rand.nextInt(100);
TimeUnit.MILLISECONDS.sleep(ss);
buf.put(ss);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static class Consumer implements Runnable {
private BoundedBuffer<Integer> buf;
public Consumer(BoundedBuffer<Integer> buf) {
this.buf = buf;
}
@Override
public void run() {
try {
TimeUnit.MILLISECONDS.sleep(rand.nextInt(100));
buf.get();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static Random rand = new Random(37);
public static void main(String[] args) throws Exception {
BoundedBuffer<Integer> buf = new BoundedBuffer<>(5);
System.setOut(new PrintStream(new FileOutputStream(
"log/BoundedBufferClient.debug")));
int i = 100;
while (i-- > 0) {
new Thread(new Consumer(buf), "Consumer").start();
new Thread(new Productor(buf), "Productor").start();
}
TimeUnit.SECONDS.sleep(3);
}
}
AbstractBoundedBuffer提供了基本的添加和获取的方法,且其中所涉及的方法都是synchronized的。BoundedBuffer继承自AbstractBoundedBuffer,它使用AbstractBoundedBuffer的添加和获取的方法构建对外的put和get方法。这两个方法都是要判断当前的状态,如果说状态不允许,则在当前对象上等待,直到状态允许,才进行下一步工作。
2. 使用Lock内的Condition对象
这种方式的效率比上一种效率更高,因为它可以在条件允许时通知某些特定的对象,而不需要通知所有的对象。这是由于内置锁(使用synchronized的方式)只能有一个相关联的条件队列,而对于Lock对象,每个Condition上都会有一个条件队列,故可以使用notify来通知其他对象,从而减少冲突的可能。
public class ConditionBoundedBuffer<T> {
protected final Lock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
private T[] items = null;
private int tail = 0, head = 0, count = 0;
@SuppressWarnings("unchecked")
public ConditionBoundedBuffer(int capacity) {
items = (T[]) new Object[capacity];
}
public void put(T t) {
lock.lock();
try {
while (count == items.length)
notFull.await();
items[tail] = t;
if (++tail == items.length) {
tail = 0;
}
++count;
notEmpty.signal();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
public T get() {
lock.lock();
try {
while (count == 0)
notEmpty.await();
T t = items[head];
items[head] = null;
if (++head == items.length) {
head = 0;
}
--count;
notFull.signal();
return t;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
}
public class ConditionBoundedBufferClient {
private static class Productor implements Runnable {
private ConditionBoundedBuffer<Integer> buf;
public Productor(ConditionBoundedBuffer<Integer> buf) {
this.buf = buf;
}
@Override
public void run() {
try {
int ss = rand.nextInt(100);
TimeUnit.MILLISECONDS.sleep(ss);
buf.put(ss);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static class Consumer implements Runnable {
private ConditionBoundedBuffer<Integer> buf;
public Consumer(ConditionBoundedBuffer<Integer> buf) {
this.buf = buf;
}
@Override
public void run() {
try {
TimeUnit.MILLISECONDS.sleep(rand.nextInt(100));
buf.get();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static final Random rand = new Random(47);
public static void main(String[] args) throws Exception {
ConditionBoundedBuffer<Integer> buf = new ConditionBoundedBuffer<>(5);
System.setOut(new PrintStream(new FileOutputStream(
"log/ConditionBoundedBufferClient.debug")));
int i = 100;
while (i-- > 0) {
new Thread(new Consumer(buf), "Consumer").start();
new Thread(new Productor(buf), "Productor").start();
}
TimeUnit.SECONDS.sleep(3);
}
}