Java Producer-Consumer Pattern Implementation

Classified in Computers

Written on in English with a size of 2.28 KB

Java Producer-Consumer Implementation

class ObjCompartido {
    private int longArray;
    private ArrayList<Object> array = new ArrayList<>();

    public ObjCompartido(int longArray) {
        this.longArray = longArray;
    }

    public synchronized void producir(Object xxx) {
        while (this.array.size() == longArray) {
            try {
                System.out.println("ESPERANDO");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.array.add(xxx);
        System.out.println("AÑADIDO");
        notifyAll();
    }

    public synchronized void consumir(Object xxx) {
        while (this.array.isEmpty()) {
            try {
                System.out.println("ESPERANDO");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.array.remove(0);
        System.out.println("BORRADO");
        notifyAll();
    }
}

Thread Classes

class HiloProducir extends Thread {
    ObjCompartido obj;
    Object xxx;

    public HiloProducir(ObjCompartido obj, Object xxx) {
        this.obj = obj;
        this.xxx = xxx;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(5000);
                obj.producir(xxx);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class HiloConsumir extends Thread {
    ObjCompartido obj;
    Object xxx;

    public HiloConsumir(ObjCompartido obj, Object xxx) {
        this.obj = obj;
        this.xxx = xxx;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(5000);
                obj.consumir(xxx);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Main Execution

public class Main {
    public static void main(String[] args) {
        ObjCompartido obj = new ObjCompartido(10);
        Thread t1 = new HiloProducir(obj, new Object());
        t1.start();
        Thread t2 = new HiloConsumir(obj, new Object());
        t2.start();
    }
}

Related entries: