* Implémenter l'interface Runnable
* Etendre la classe thread.
Dans l'optique de faire un code robuste, je recommande d'implémenter l'interface Runnable, elle évite de se perdre dans la profusion de méthodes offertes par la classe Thread.
Les threads servent à paralléliser les tâches. Deux opérations clés sont importantes.
* Le départ
* La synchronisation (jointure)
Le plus délicat est de comprendre l'utilisation du wait et du notify. Pour être utilisé le wait et le notify doivent être placé sur la même classe (Ici le ThreadGroup)
Ce bloc lance 25 threads// Ici nous construisons sans les déclencher tous les thread dont nous avons besoinsList<thread> threads = new ArrayList<thread>();ThreadGroup threadGroup = new ThreadGroup("MyThreadList");for (int i = 0; i < thread =" new" thread =" new"> 0) { System.out.println("Threads restants : " + threadGroup.activeCount()); // Attente d'une nçotification threadGroup.wait();}}
Voici l'implémentation de Runnable
public class MyThread implements Runnable {public MyThread(ThreadGroup tg) { threadGroup = tg;}public void run() {System.out.prinln("Effectue le traitement");// Ici le ThreadGroup est notifiésynchronized (threadGroup) { // Notification du parent threadGroup.notify(); }}
2 commentaires:
Enregistrer un commentaire