Copiez le code comme suit :
état du colis ;
importer java.util.ArrayList ;
importer java.util.List ;
importer java.util.concurrent.locks.Condition ;
importer java.util.concurrent.locks.Lock ;
importer java.util.concurrent.locks.ReentrantLock ;
/**
* Utilisez Lock and Condition pour mettre en œuvre le modèle producteur-consommateur
* @author le fera
*
*/
classe publique ProducerConsumerDemo {
public static void main (String[] arguments) {
int producteurCount = 10 ;
int consumerCount = 15 ;
final ProducerConsumerDemo pcd = new ProducerConsumerDemo(5); // La taille du tampon est de 5
Thread[] producteurThreads = nouveau Thread[producterCount];
for(int i = 0; i < producteurCount; i++) {
producteurThreads[i] = new Thread("producteur" + (i+1)) {
@Outrepasser
public void run() {
pcd.product();
}
} ;
}
Thread[] consumerThreads = nouveau Thread[consumerCount];
pour(int j = 0; j < consumerCount; j++) {
consumerThreads[j] = new Thread("consommateur" + (j+1)) {
@Outrepasser
public void run() {
pcd.consume();
}
} ;
}
//Démarrer le fil de discussion producteur-consommateur
for(int i = 0; i < producteurCount; i++) {
producteurThreads[i].start();
}
pour(int j = 0; j < consumerCount; j++) {
consumerThreads[j].start();
}
}
privé statique final int DEFAULT_BUFFER_SIZE = 10;
private int bufferSize; // taille du tampon
liste privée<Object> bufferList ;
verrou final privé = new ReentrantLock (true);
condition finale privée condition = lock.newCondition();
public ProducerConsumerDemo (int bufferSize) {
this.bufferSize = bufferSize > 0 ? bufferSize : DEFAULT_BUFFER_SIZE;
bufferList = new ArrayList<Object>(bufferSize);
}
// Production
public void produire() {
lock.lock(); // verrouiller
essayer {
while(bufferList.size() == bufferSize) { // Le tampon est plein
System.out.println("Attente du producteur, thread : " + Thread.currentThread().getName());
condition.attendre();
}
// Production
bufferList.add(new Object());
System.out.println("Le producteur en produit un, maintenant taille du tampon : "
+ bufferList.size() + ", et thread : " + Thread.currentThread().getName());
condition.signalAll(); // Notifier les consommateurs
} catch (InterruptedException e) {
e.printStackTrace();
} enfin {
lock.unlock();
}
}
// Consommation
public void consommer() {
lock.lock(); // verrouiller
essayer {
while(bufferList.isEmpty()) { // Le tampon est vide
System.out.println("Attente du consommateur, thread : " + Thread.currentThread().getName());
condition.attendre();
}
// Consommation
bufferList.remove(0); // Supprime un de la tête de la liste chaînée
System.out.println("Consommateur consommateur, maintenant taille du tampon : "
+ bufferList.size() + ", et thread : " + Thread.currentThread().getName());
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} enfin {
lock.unlock();
}
}
}