La copie de code est la suivante:
Package com.yao;
Importer java.util.concurrent.CountDownLatch;
Importer java.util.concurrent.executorService;
Importer java.util.concurrent.executors;
/ **
* CountdownLatch est un compteur, qui a un numéro initial,
* Le fil en attente de ce compteur doit attendre que le compteur compte à zéro avant de continuer.
* /
classe publique CountdownLatchTest {
/ **
* Le thread qui initialise le composant
* /
Classe statique publique ComponentThread implémente Runnable {
// Comptoir
CountdownLatch Latch;
// ID de composant
int id;
// Construire la méthode
Public ComponentThread (CountdownLatch Latch, int id) {
this.latch = latch;
this.id = id;
}
public void run () {
// initialise le composant
System.out.println ("Initialisation du composant" + id);
essayer {
Thread.Sleep (500 * id);
} catch (InterruptedException e) {
}
System.out.println ("composant" + id + "initialisé!");
// décrément le compteur par un
latch.CountDown ();
}
}
/ **
* Démarrez le serveur
* /
public static void starterver () lève une exception {
System.out.println ("Le serveur commence.");
// initialise un compte à rebours avec une valeur initiale de 3
CountdownLatch Latch = new CountdownLatch (3);
// Démarrer 3 threads pour démarrer respectivement 3 composants
ExecutorService Service = exécutor.NewCachedThreadPool ();
Service.Submit (nouveau composantThread (Latch, 1));
Service.Submit (nouveau composantThread (Latch, 2));
Service.Submit (nouveau composantThread (Latch, 3));
service.shutdown ();
// en attente de la fin de l'initialisation de 3 composants
latch.Await ();
// Lorsque tous les trois composants requis sont terminés, le serveur peut continuer
System.out.println ("Server est en place!");
}
public static void main (String [] args) lève une exception {
COUNTDOWNLATCHTEST.STARTSERVER ();
}
}