CountDownLatch的基础使用

若如初见. 提交于 2020-01-13 02:26:03

在实际开发过程中,有一些需要并行执行的任务,通过CountDownLatch可以轻松实现这个功能,以下是初期使用的demo

1、先写两个线程类


import lombok.Data;

import java.util.HashMap;
import java.util.concurrent.CountDownLatch;


@Data
public class CountDownLatchThread1 implements Runnable{

    private HashMap<String,Integer> countMap ;
    private CountDownLatch countDownLatch  ;
    private Integer count = 0;

    public CountDownLatchThread1(HashMap<String,Integer> countMap, CountDownLatch countDownLatch) {
        this.countMap = countMap;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        int count = (int)(Math.random()*(100));
        countMap.put("num1",count);
        System.out.println("线程1 num = " + count);
        countDownLatch.countDown();
    }
}

import lombok.Data;

import java.util.HashMap;
import java.util.concurrent.CountDownLatch;


@Data
public class CountDownLatchThread2 implements Runnable{

    private HashMap<String,Integer> countMap ;
    private CountDownLatch countDownLatch  ;
    private Integer count = 0;

    public CountDownLatchThread2(HashMap<String,Integer> countMap, CountDownLatch countDownLatch ) {
        this.countMap = countMap;
        this.countDownLatch = countDownLatch;
        countDownLatch.countDown();
    }

    @Override
    public void run() {
        int count = (int)(Math.random()*(100));
        countMap.put("num2",count);
        System.out.println("线程2 num = " + count );
        countDownLatch.countDown();
    }
}

2、通过CountDownLatch来实现并行任务的功能


import com.alibaba.fastjson.JSON;
import com.boot.diamonds.utils.countDownLatch.CountDownLatchThread1;
import com.boot.diamonds.utils.countDownLatch.CountDownLatchThread2;

import java.util.HashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;

import static java.util.concurrent.Executors.newFixedThreadPool;


public class CountDownLatchTest {

    private static ExecutorService fixedThreadPool = newFixedThreadPool(2);
    private static HashMap<String,Integer> countMap = new HashMap<>();

    public static void main(String[] args) throws InterruptedException {
        final CountDownLatch countDownLatch = new CountDownLatch(2);

        fixedThreadPool.execute(new CountDownLatchThread1(countMap,countDownLatch));
        fixedThreadPool.execute(new CountDownLatchThread2(countMap,countDownLatch));

        countDownLatch.await();
        System.out.println("最终结果 = " + JSON.toJSONString(countMap));


    }
}

 

 

以下是运行结果

可以将这些代码改造一下,改成适合自己的代码。至于CountDownLatch的实现原理,后期有空会在下面补上

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!