1.Countdownlatch is a synchronous helper class, like a countdown counter, when an object is created, the initial value is set by the constructor method, and the await () method that calls the Countdownlatch object is in a wait state. Calling the countdown () method will reduce the counter by 1, and when the count reaches 0 o'clock, all the waiting or a single person waits for execution to begin.
2. MicroServices make data acquisition sources diverse, and the data required by the client is a combination of data, which requires a consolidation on the server
3. When acquiring customer data, obtain relevant data from multiple sources to the client,
1) Total current customer consumption (in customer service)
2) Ranking of current customer consumption in all customers (in customer sequencing service)
ImportJava.util.Random;ImportJava.util.concurrent.CountDownLatch; Public classApp { Public Static voidMain (string[] args)throwsinterruptedexception {countdownlatch latch=NewCountdownlatch (2); Work Worl=NewWork (latch); Work Wor2=NewWork (latch); Worl.start (); Wor2.start (); Latch.await (); CustomerInfo CustomerInfo=NewCustomerInfo (); Customerinfo.setconsumesum ((int) Worl.getresult ()); Customerinfo.setsortinallcustomer ((int) Wor2.getresult ()); System.out.println (CustomerInfo); }}classcustomerinfo{Private intSortinallcustomer; Private intconsumesum; Public intGetsortinallcustomer () {returnSortinallcustomer; } Public voidSetsortinallcustomer (intSortinallcustomer) { This. Sortinallcustomer =Sortinallcustomer; } Public intgetconsumesum () {returnconsumesum; } Public voidSetconsumesum (intconsumesum) { This. Consumesum =consumesum; } @Override PublicString toString () {returnString.Format ("Current customer consumption%d, ranking%d among all users", Getconsumesum (), Getsortinallcustomer ()); }}classWorkextendsthread{PrivateCountdownlatch latch; PrivateObject result; PublicWork (Countdownlatch latch) { This. latch=latch; } @Override Public voidrun () {Try{random random=NewRandom (); intms = Random.nextint (10) +1; Thread.Sleep (1000*ms); This. result=MS; } Catch(interruptedexception e) {e.printstacktrace (); } finally{latch.countdown (); } } PublicObject GetResult () {returnresult; }}
Countdownlatch of Java Concurrent task completion