Basket类:生产者消费者需要互斥访问的资源
class Basket {
int capacity;
int num;
Basket(int capacity) {
this.capacity = capacity;
}
boolean isEmpty() {
return num == 0 ? true : false;
}
boolean isFull() {
return num == capacity ? true : false;
}
void put() {
num++;
}
void get() {
num--;
}
int getNum() {
return num;
}
}
Producer类:生产者
class Producer implements Runnable {
Basket basket;
Producer(Basket basket) {
this.basket = basket;
}
@Override
public void run() {
while (true) {
synchronized (basket) {
while (basket.isFull()) {
try {
basket.wait();
} catch (InterruptedException e) {
}
}