public class ProdCons { private Buffer buff = new Buffer(); // Constructor public ProdCons() { Productor prod = new Productor(); Consumidor cons = new Consumidor(); for (int i = 0; i < 4; i++) { new Thread(prod).start(); } for (int i = 0; i < 4; i++) { new Thread(cons).start(); } } private class Buffer { private static final int DBUFF = 1; private int n = 0, in = 0, out = 0; private int[] b = new int[DBUFF]; public synchronized void agregar(int v) throws InterruptedException { while (n == DBUFF) { wait(); } b[in] = v; in = (in + 1) % DBUFF; n = n + 1; notifyAll(); } public synchronized int sacar() throws InterruptedException { while (n == 0) { wait(); } int v = b[out]; out = (out + 1) % DBUFF; n = n - 1; notifyAll(); return v; } } private class Productor implements Runnable { @Override public void run() { int i = 0; while (true) { try { buff.agregar(i++); } catch (Exception e) { e.printStackTrace(); } } } } private class Consumidor implements Runnable { @Override public void run() { while (true) { try { System.out.println(Thread.currentThread().getId() + ": " + buff.sacar()); } catch (Exception e) { e.printStackTrace(); } } } } public static void main(String[] args) { new ProdCons(); } }