Patrón Productor Consumidor en Java con Hilos y Sincronización

Informática y Telecomunicaciones3,26 KB

Implementación del Patrón Productor-Consumidor en Java

A continuación se presenta el código fuente en Java que implementa el clásico problema de concurrencia del productor-consumidor utilizando hilos (Thread), un búfer compartido y métodos sincronizados para gestionar la creación y empaquetado de hamburguesas.

Clase RobotEmpaquetar

class RobotEmpaquetar extends Thread {
    Buffer buff;
    String tipo;

    public RobotEmpaquetar(Buffer buff, String tipo) {
        this.buff = buff;
        this.tipo = tipo;
    }

    @Override
    public void run() {
        while(true) {
            try {
                Thread.sleep(1000);
                buff.consumir(this.tipo);
            } catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

Clase RobotProductor

class RobotProductor extends Thread {
    Buffer buff;
    ArrayList<String> tipos = new ArrayList<>(Arrays.asList("Smash", "Chicken", "Vegan"));
    
    public RobotProductor(Buffer buff) {
        this.buff = buff;
    }

    @Override
    public void run() {
        while (true) {
            int tiempoEspera = (int)(Math.random()*31)+20;
            int random = (int) (Math.random() * tipos.size());
            String tipo = tipos.get(random);
            try {
                Thread.sleep(tiempoEspera);
                buff.producir(tipo);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Clase Buffer

class Buffer {
    private int elementoMaximo;
    private ArrayList<String> cola = new ArrayList<>();

    public Buffer(int elementoMaximo) {
        this.elementoMaximo = elementoMaximo;
    }

    public synchronized void producir(String contenido) {
        while(this.cola.size() == elementoMaximo) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        this.cola.add(contenido);
        System.out.println("Hamburguesa de " + contenido + " hecha.");

        notifyAll();
    }

    public synchronized String consumir(String tipoDeseado) {
        while(this.cola.isEmpty() || !this.cola.get(0).equals(tipoDeseado)) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        String elem = this.cola.remove(0);
        System.out.println("Hamburguesa de "  + elem + " empaquetada.");
        notifyAll();

        return elem;
    }
}

Clase Principal ProductorConsumidor

public class productorConsumidor {
    public static void main(String[] args) {
        Buffer buff = new Buffer(10);
        Thread robotProducir = new RobotProductor(buff);
        Thread robotEmpaquetador1 = new RobotEmpaquetar(buff, "Smash");
        Thread robotEmpaquetador2 = new RobotEmpaquetar(buff, "Chicken");
        Thread robotEmpaquetador3 = new RobotEmpaquetar(buff, "Vegan");

        robotProducir.start();
        robotEmpaquetador1.start();
        robotEmpaquetador2.start();
        robotEmpaquetador3.start();
    }
}

Descargar

PDF Word HTML