在实际开发过程中,有一些需要并行执行的任务,通过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的实现原理,后期有空会在下面补上
来源:CSDN
作者:种BUG
链接:https://blog.csdn.net/qq_32719003/article/details/103863385