需要了解的接口是Lock和Condition
class Consumer implements Runnable {
private Resource resource;
public Consumer(Resource r) {
this.resource = r;
}
public void run() {
try {
while (true) {
resource.read();
}
} catch (Exception e) {
}
}
}
class Producer implements Runnable {
private Resource resource;
public Producer(Resource r) {
this.resource = r;
}
public void run() {
try {
while (hasMoreValue()) {
int value = nextValue();
resource.write(value);
}
} catch (Exception e) {
}
}
private boolean hasMoreValue() {
return true;
}
private int nextValue() {
return 0;
}
}
class Resource {
private final int CAPACITY = 2;
private LinkedList<Integer> queue = new LinkedList<Integer>();
private Lock lock = new ReentrantLock();
private Condition notEmpty = lock.newCondition();
private Condition notFull = lock.newCondition();
public void write(int value) throws InterruptedException {
final Lock lock = this.lock;
lock.lock();
try {
while (queue.size() == CAPACITY) {
notFull.await();
}
insert(value);
} finally {
lock.unlock();
}
}
public int read() throws InterruptedException {
final Lock lock = this.lock;
lock.lock();
try {
while (queue.size() == 0) {
notEmpty.await();
}
return extract();
} finally {
lock.unlock();
}
}
private int extract() {
int value = queue.peek();
notFull.signal();
return value;
}
private void insert(int value) {
queue.add(value);
notEmpty.signal();
}
}