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 78 79 80 81 82
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MultiThread {
Map<Personne, List<Animal>> mapP = new HashMap<>();
List<Animal> list = new ArrayList<>();
public void init() {
Personne p0 = new Personne("Dupont", "Eric", 00);
Personne p1 = new Personne("Durant", "Etienne", 10);
Personne p2 = new Personne("Newton", "Isaac", 20);
Personne p3 = new Personne("Sartre", "Paul", 30);
Animal a0 = new Animal("Chien");
Animal a1 = new Animal("Chat");
Animal a2 = new Animal("Lion");
Animal a3 = new Animal("Tigre");
list.add(a0);
list.add(a1);
list.add(a2);
list.add(a3);
mapP.put(p0, list);
mapP.put(p1, list);
mapP.put(p2, list);
mapP.put(p3, list);
}
// notre exécuteur, qui renvoie un résultat de type String
public class MyWorker implements Callable<String> {
private Entry<Personne, List<Animal>> key;
// je passe l'Entry par fainéantise, normalement on devrait passer les deux éléments séparemment
public MyWorker(Entry<Personne, List<Animal>> key) {
this.key = key;
}
@Override
public String call() throws Exception {
StringBuilder sb = new StringBuilder();
sb.append(Thread.currentThread().getName() + " M. " + key.getKey().getNom() + " Possede les animaux suivant : ");
for (Animal animal : key.getValue()) {
sb.append(animal.getType() + " ");
}
return sb.toString();
}
}
// throws Exception mais normalement on devrait gérer mieux les exceptions, ici aussi, fainéantise de ma part, mais c'est pour l'exemple
public static void main(String[] args) throws Exception {
MultiThread mt = new MultiThread();
mt.init();
// création d'un pool de threads en fonction du nombre de processeurs
ExecutorService ex = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
// notre liste de "futurs" résultats
List<Future<String>> results = new ArrayList<>();
for (Entry<Personne, List<Animal>> key : mt.mapP.entrySet()) {
// lancement d'un thread et ajout du résultat à la liste finale
results.add(ex.submit(mt.new MyWorker(key)));
// chaque submit lance le thread
}
// lecture des résultats, chaque get récupère un résultat (et attend un résultat si besoin)
for (Future<String> value : results) {
System.out.println(value.get());
}
// fermeture du pool (obligatoire)
ex.shutdown();
}
} |
Partager