首页 > 代码库 > java 并发完成任务之CountDownLatch

java 并发完成任务之CountDownLatch

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