1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
package productorconsumidor; import static java.lang.Thread.sleep; public class ProductorConsumidor { public static void main(String[] args) { Recurso recurso = new Recurso(); Producir p1 = new Producir(recurso, 1); Consumir c1 = new Consumir(recurso, 1); p1.start(); c1.start(); } } class Recurso { private int contenido; private boolean available = false; public synchronized int get() { while (available == false) { try { wait(); } catch (InterruptedException e) { } } available = false; notifyAll(); return contenido; } public synchronized void put(int valor) { while (available == true) { try { wait(); } catch (InterruptedException e) { } } contenido = valor; available = true; notifyAll(); } } class Consumir extends Thread { private Recurso recursoc; private int number; public Consumir(Recurso recurso, int number) { recursoc = recurso; this.number = number; } public void run() { int value = 0; for (int i = 0; i < 10; i++) { value = recursoc.get(); System.out.println("Consumir recurso" + this.number+ " valor: " + value); } } } class Producir extends Thread { private Recurso recursop; private int number; public Producir(Recurso recurso, int number) { recursop = recurso; this.number = number; } public void run() { for (int i = 0; i < 20; i++) { recursop.put(i); System.out.println("Producir recurso" + this.number + " valor: " + i); try { sleep((int)(Math.random() * 100)); } catch (InterruptedException e) { } } } } |