transparent
// Producteur.java public class Producteur extends Thread { private Buffer buf; private int identité; public Producteur(Buffer c, int n) { buf = c; this.identité = n; } public void run() { for (int i = 0; i < 100; i++) { buf.mettre(i); System.out.println("Producteur #" + this.identité + " met : " + i); try { sleep((int)(Math.random() * 100));} catch (InterruptedException e) { } } } }
public class Consommateur extends Thread { private Buffer buf; private int identité; public Consommateur(Buffer c, int n) { buf = c; this.identité = n; } public void run() { int val = 0; for (int i = 0; i < 10; i++) { val = buf.prendre(); System.out.println("Consommateur #" + this.identité + " prend: " + val); } } }
public class Buffer { private int valeur; private boolean available = false; public synchronized int prendre() { while (available == false) { try {wait();} catch (InterruptedException e) { } } available = false; notifyAll(); return valeur; } public synchronized void mettre(int val) { while (available == true) { try {wait();} catch (InterruptedException e) { } } valeur = val;available = true; notifyAll(); } }
// Main.java public class Main { public static void main(String[] args) { Buffer c = new Buffer(); Producteur p1 = new Producteur(c, 1); Producteur p2 = new Producteur(c, 2); Producteur p3 = new Producteur(c, 3); Consommateur c1 = new Consommateur(c, 1); Consommateur c2 = new Consommateur(c, 2); Consommateur c3 = new Consommateur(c, 3); p1.start();p2.start();p3.start(); c1.start();c2.start();c3.start(); } }