import java.util.ArrayList; import java.util.List; import java.util.Random; //Producer-Consumer problem public class ProducerConsumerMain { public static final int N_CONSUMER = 10; public static final int N_PRODUCER = 20; public static void main(String[] args) { Puffer puffer = new Puffer(10); for (int i = 0; i< N_CONSUMER; i++) { Thread t = new Thread(new Consumer(puffer)); t.start(); } for (int i = 0; i< N_PRODUCER; i++) { Thread t = new Thread(new Producer(puffer)); t.start(); } } } //Storage/Warehouse class Puffer { private int maxSize; List list = new ArrayList(); public Puffer(int maxSize) { super(); this.maxSize = maxSize; } //Put a "product" (number) in the storage public synchronized void deposit(int product) { System.out.println("+ deposit"); while(list.size() == maxSize) { try { //the storage is full, waiting for free space System.out.println("wait in deposit"); wait(); System.out.println("wait ended in deposit"); } catch (InterruptedException e) { e.printStackTrace(); } } list.add(product); System.out.println("deposit " + list.size()); //notify others to check the conditions again notifyAll(); } //Get a "product" (number) from the storage public synchronized int extract() { System.out.println("- extract"); while(list.isEmpty()) { try { //the storage is empty, waiting for a product System.out.println("wait in extract"); wait(); System.out.println("wait ended in extract"); } catch (InterruptedException e) { e.printStackTrace(); } } int product = list.remove(list.size()-1); System.out.println("extract " + list.size()); //notify others to check the conditions again notifyAll(); return product; } } class Producer implements Runnable { private Puffer puffer; private Random random = new Random(); public Producer(Puffer puffer) { super(); this.puffer = puffer; } @Override public void run() { //Put a "product" (number) in the storage puffer.deposit(random.nextInt()); } } class Consumer implements Runnable { private Puffer puffer; public Consumer(Puffer puffer) { super(); this.puffer = puffer; } @Override public void run() { //Get a "product" (number) from the storage puffer.extract(); } }