コードコピーは次のとおりです。
パッケージcom.yao;
java.util.concurrent.countdownlatchをインポートします。
java.util.concurrent.executorserviceをインポートします。
java.util.concurrent.executorsをインポートします。
/**
* CountDownLatchはカウンターで、初期の数字があります。
*このカウンターを待っているスレッドは、継続する前にカウンターがゼロにカウントされるまで待つ必要があります。
*/
パブリッククラスCountDownLatchTest {
/**
*コンポーネントを初期化するスレッド
*/
public static class componentthreadは実行可能{
//カウンター
CountDownLatchラッチ;
//コンポーネントID
int id;
//構築方法
public componentthread(countdownlatch latch、int id){
this.latch = latch;
this.id = id;
}
public void run(){
//コンポーネントを初期化します
system.out.println( "componentの初期化" + id);
試す {
thread.sleep(500 * id);
} catch(arternedexception e){
}
system.out.println( "component" + id + "initialized!");
//カウンターを1つずつ減らします
latch.countdown();
}
}
/**
*サーバーを起動します
*/
public static void startServer()スロー例外{
System.out.println( "Server Is Start。");
//初期値が3のCountDownLatchを初期化します
CountDownLatch latch = new CountDownLatch(3);
// 3つのスレッドを起動して、それぞれ3つのコンポーネントを開始します
executorservice service = executors.newcachedthreadpool();
service.submit(new ComponentThread(Latch、1));
service.submit(new ComponentThread(Latch、2));
service.submit(new ComponentThread(Latch、3));
service.shutdown();
// 3つのコンポーネントの初期化が完了するのを待っています
latch.await();
//必要な3つのコンポーネントがすべて完了すると、サーバーは続行できます
system.out.println( "サーバーIS UP!");
}
public static void main(string [] args)スロー例外{
CountDownLatchTest.StartServer();
}
}