1. 使用syncronize实现
static Object[] items = new Object[100];
static int takePoint = 0, putPoint = 0;
static AtomicInteger cnt = new AtomicInteger(0);
public synchronized static void produce(Object o) throws InterruptedException {
while(cnt.get() == items.length) { //如果写队列满了,阻塞
Thread.sleep(1000);
}
items[putPoint++] = o;
cnt.getAndIncrement();
if(putPoint == items.length) putPoint = 0;
}
public synchronized static Object consume() throws InterruptedException {
while(cnt.get() == 0) { //如果读队列满了,阻塞
Thread.sleep(1000);
}
Object res = items[takePoint++];
cnt.getAndDecrement();
if(takePoint == items.length) takePoint = 0;
return res;
}
2. 基于reentrantlock 和 condition实现
static final ReentrantLock lock = new ReentrantLock();
static final Condition read = lock.newCondition(), write = lock.newCondition();
static Object[] items = new Object[100];
static AtomicInteger cnt = new AtomicInteger(0), takePoint = new AtomicInteger(0),
putPoint = new AtomicInteger(0);
public static void produce(Object o) throws InterruptedException {
lock.lock();
try {
if(cnt.get() == items.length) {
write.await(); //如果写队列满了,写线程阻塞
}
items[putPoint.get()] = o;
if(putPoint.getAndIncrement() + 1 == items.length) putPoint.set(0);
cnt.getAndIncrement();
read.signal(); //通知读线程
}finally {
lock.unlock();
}
}
public static Object consume() throws InterruptedException {
lock.lock();
Object res = null;
try {
if(cnt.get() == 0) {
read.await(); //如果读队列空了,读线程阻塞
}
res = items[takePoint.get()];
cnt.getAndDecrement();
if(takePoint.getAndIncrement() + 1 == items.length) takePoint.set(0);
write.signal(); //通知写线程
return res;
}finally {
lock.unlock();
}
}