next up previous contents
suivant: Barrière de synchronisation monter: wait, notify, notifyAll précédent: Sémaphore   Table des matières

Producteurs/Consommateurs

Dans cet exemple de producteurs/consommateurs partageant un buffer borné à une seule place, il s'agit pour les producteurs et les consommateurs de se synchroniser sur le buffer. Un producteur doit attendre que le buffer soit vide pour mettre la valeur produite dans le buffer. Le producteur attend que le buffer soit plein pour consommer la valeur.



transparent
Producteur


// 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) { }
       }
    }
}


transparent
Consommateur


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);
        }
    }
}


transparent
Buffer


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();
    }
}


transparent
Main


// 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();
        }
    }




Hugues Fauconnier 2002-01-11