標籤:建立對象 對象 color getc ted 客戶 import 方法 exti
1.CountDownLatch是一個同步輔助類,猶如倒計時計數器,建立對象時通過構造方法設定初始值,調用CountDownLatch對象的await()方法則處於等待狀態,調用countDown()方法就將計數器減1,當計數到達0時,則所有等待者或單個等待者開始執行。
2.微服務使資料擷取來源多樣化,而用戶端所需要的資料是組合資料,這樣就需要在服務端做一個拼裝
3.如擷取客戶資料時要從多個來源擷取相關的資料給用戶端,
1)當前客戶消費總額 (在客戶服務裡)
2)當前客戶消費總額在所有客戶裡的排序 (在客戶排序服務裡)
import java.util.Random;import java.util.concurrent.CountDownLatch;public class App { public static void main(String[] args) throws InterruptedException { CountDownLatch latch=new CountDownLatch(2); Work worl = new Work(latch) ; Work wor2 = new Work(latch) ; worl.start(); wor2.start(); latch.await(); CustomerInfo customerInfo=new CustomerInfo(); customerInfo.setConsumeSum((int)worl.getResult()); customerInfo.setSortInAllCustomer((int)wor2.getResult()); System.out.println(customerInfo); }}class CustomerInfo{ private int sortInAllCustomer; private int consumeSum; public int getSortInAllCustomer() { return sortInAllCustomer; } public void setSortInAllCustomer(int sortInAllCustomer) { this.sortInAllCustomer = sortInAllCustomer; } public int getConsumeSum() { return consumeSum; } public void setConsumeSum(int consumeSum) { this.consumeSum = consumeSum; } @Override public String toString() { return String.format("當前客戶消費%d,在所有使用者中排名第%d",getConsumeSum(),getSortInAllCustomer()); }}class Work extends Thread{ private CountDownLatch latch; private Object result; public Work(CountDownLatch latch) { this.latch=latch; } @Override public void run() { try { Random random=new Random(); int ms = random.nextInt(10)+1; Thread.sleep(1000*ms); this.result=ms; } catch (InterruptedException e) { e.printStackTrace(); } finally { latch.countDown(); } } public Object getResult() { return result; }}
java 並發完成任務之CountDownLatch