java 並發完成任務之CountDownLatch

來源:互聯網
上載者:User

標籤:建立對象   對象   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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.