You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
89 lines
2.0 KiB
Java
89 lines
2.0 KiB
Java
import java.util.ArrayList;
|
|
|
|
class Producteur implements Runnable {
|
|
static final int MAXFILE = 5;
|
|
static final int MAXMESSAGES = 50;
|
|
private ArrayList<String> messages;
|
|
private int nbMessage;
|
|
|
|
public Producteur() {
|
|
messages = new ArrayList<String>();
|
|
nbMessage = 0;
|
|
}
|
|
|
|
public void run(){
|
|
try {
|
|
while (nbMessage < MAXMESSAGES) {
|
|
insererMessage();
|
|
System.out.println("Message numero "+nbMessage+" produit");
|
|
nbMessage++;
|
|
Thread.sleep(1000);
|
|
}
|
|
}
|
|
catch (InterruptedException e) {}
|
|
}
|
|
|
|
private synchronized void insererMessage () {
|
|
while (messages.size() == MAXFILE) {
|
|
System.out.println("File pleine");
|
|
try{
|
|
this.wait();
|
|
}
|
|
catch(InterruptedException e){
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
messages.add(new java.util.Date().toString());
|
|
}
|
|
|
|
public synchronized String recupererMessage() {
|
|
while (messages.size() == 0) {
|
|
System.out.println("File vide");
|
|
try{
|
|
this.wait();
|
|
}
|
|
catch(InterruptedException e){
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
String message = (String)messages.get(0);
|
|
messages.remove(0);
|
|
return message;
|
|
}
|
|
}
|
|
|
|
class Consommateur implements Runnable {
|
|
static final int MAXMESSAGES = 50;
|
|
private int nbMessage;
|
|
|
|
Producteur producteur;
|
|
Consommateur(Producteur p) {
|
|
producteur = p ;
|
|
nbMessage++;
|
|
}
|
|
|
|
public void run(){
|
|
try {
|
|
while (nbMessage < MAXMESSAGES) {
|
|
String message = producteur.recupererMessage();
|
|
System.out.println("Message numero "+nbMessage+" recu : " +message);
|
|
nbMessage++;
|
|
Thread.sleep(2000);
|
|
}
|
|
}
|
|
catch (InterruptedException e) {}
|
|
}
|
|
}
|
|
|
|
public class Distributeur {
|
|
public static void main(String[] args){
|
|
Producteur prod = new Producteur();
|
|
Thread tProd = new Thread(prod);
|
|
tProd.start();
|
|
|
|
Consommateur conso = new Consommateur(prod);
|
|
Thread tConso = new Thread(conso);
|
|
tConso.start();
|
|
}
|
|
}
|