ImportJava.util.concurrent.CountDownLatch;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;/*** Simulation of the 100-meter race, 10 players are ready, only waiting for the referee commanded. When everyone gets to the finish line, the game is over. * @authorLiuchao **/ Public classActor { Public Static voidMain (string[] args)throwsinterruptedexception {//10 Athletes FinalCountdownlatch count =NewCountdownlatch (10); //thread pool for Java FinalExecutorservice Executorservice = Executors.newfixedthreadpool (5); for(intindex=1;index<=10;index++){ Final intNumber =index; Executorservice.submit (NewRunnable () { Public voidrun () {Try {
Thread.Sleep ((Long) (Math.random () *10000)); System.out.println ( number+ ": Arrived"); } Catch(interruptedexception e) {e.printstacktrace (); } finally{ //The athlete arrives at the end, count counts minus oneCount.countdown (); } } }); } System.out.println ("Game Started"); //wait for count to change to 0, otherwise the game will never end.count.await (); System.out.println ("Game over"); //turn off the thread poolExecutorservice.shutdown (); }}
Run results
Game Started
5:arrived
1:arrived
2:arrived
3:arrived
8:arrived
4:arrived
6:arrived
9:arrived
7:arrived
10:arrived
Game over
A small example of Java thread pool Executorservice and Countdownlatch