A small example of Java thread pool Executorservice and Countdownlatch

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.