import java.util.LinkedList;
import java.util.Queue;
public class test {
public static void main(String[] args) {
Storage storage = new Storage();
for (int i = 0; i < 3; i++) {
new Producer("Producer-" + i, storage).start();
}
for (int i = 0; i < 2; i++) {
new Consumer("Consumer-" + i, storage).start();
}
}
}
class Storage {
private final Queue<Object> items = new LinkedList<>();
private final int MAX_SIZE = 10;
private Integer item=0;
public synchronized void put() throws InterruptedException {
while (items.size() >= MAX_SIZE) {
wait();
}
item = item+1;
items.offer(item);
System.out.println(Thread.currentThread().getName() + " put " +item.toString()+ ", current size: " + items.size());
notifyAll();
}
public synchronized Object take() throws InterruptedException {
while (items.isEmpty()) {
wait();
}
Object item = items.poll();
System.out.println(Thread.currentThread().getName() + " take "+item.toString()+", current size: " + items.size());
notifyAll();
return item;
}
}
class Producer extends Thread {
private final Storage storage;
public Producer(String name, Storage storage) {
super(name);
this.storage = storage;
}
@Override
public void run() {
try {
while (true) {
storage.put();
Thread.sleep((long) (Math.random() * 1000));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
class Consumer extends Thread {
private final Storage storage;
public Consumer(String name, Storage storage) {
super(name);
this.storage = storage;
}
@Override
public void run() {
try {
while (true) {
storage.take();
Thread.sleep((long) (Math.random() * 1000));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}