// teste de uma produtora com mais de uma consumidodra // todo tipo de buffer implementa esta interface interface BufferIf { public void poe(String t, String s); public String tira(String t, int c); } // ------------------------------------------------ // buffer1 tem lugar para apenas um elemento class Buffer1 implements BufferIf{ private String segura; private boolean ocupada = false; Buffer1() {} public synchronized void poe(String t, String s) { while (ocupada) { try { this.wait(); } catch (InterruptedException ie) { System.out.println(ie); } } segura = s; ocupada = true; System.out.println(t+" b1 poe - "+s); this.notify(); } public synchronized String tira(String t, int c) { while (!ocupada) { try { this.wait(); } catch (InterruptedException ie) { System.out.println(ie); } } String s = segura; ocupada = false; System.out.println(t+" b1 tira - "+s+" total thread: "+c); this.notify(); return s; } } // fim Buffer1 // ------------------------------------------------ // bufferN tem lugar para N elementos class BufferN implements BufferIf{ private String [] segura; private int tam, i, o; // ponteiros de entrada e saida de dados BufferN(int n) { tam = n; segura = new String[tam]; i=0; o=0; } private boolean ocupado() { return (((i+1)%tam)==o); } private boolean vazio() { return i==o; } private void incrIn() { i = (i+1)%tam; } private void incrOut() { o = (o+1)%tam; } private int in() { return i; } private int out() { return o; } public synchronized void poe(String t, String s) { while (ocupado()) { try { this.wait(); } catch (InterruptedException ie) { System.out.println(ie); } } segura[in()] = s; System.out.println(t+" bn poe - "+s); incrIn(); this.notifyAll(); } public synchronized String tira(String t, int c) { while (vazio()) { try { this.wait(); } catch (InterruptedException ie) { System.out.println(ie); } } String s = segura[out()]; incrOut(); System.out.println(t+" bn tira - "+s+" total thread: "+c); this.notifyAll(); return s; } } // fim BufferN class Consumidora extends Thread { private String nome; private BufferIf b; private int cont = 0; Consumidora(String _nome, BufferIf _b){ nome = _nome; b = _b; }; public void run() { while(true) { b.tira(nome,cont++); } } } class Produtora extends Thread { private String nome; private BufferIf b; Produtora(String _nome, BufferIf _b){ nome = _nome; b = _b; }; public void run() { int cont = 0; String m; while(cont<1000) { m = "msg"+cont++; b.poe(nome,m); } } } public class TesteThreadsProdCons2 { public static void main(String []args) { // Buffer1 b = new Buffer1(); BufferN b = new BufferN(5); Produtora p1 = new Produtora("P1",b); Consumidora c1 = new Consumidora("C1",b); Consumidora c2 = new Consumidora("C2",b); p1.start(); c1.start(); c2.start(); } // fim main } // fim classe