Java并发编程:CountdownLatch使用

翻译过来是倒计时锁,又叫倒计时门闩,会让一个线程等待其他线程完成倒计时后才会恢复运行,是 join 功能的一个扩展

class Test1111{
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);
        new Thread(() -> {
            log.debug("begin...");
            sleep(1);
            latch.countDown();
            log.debug("end...{}", latch.getCount());
        }).start();
        new Thread(() -> {
            log.debug("begin...");
            sleep(2);
            latch.countDown();
            log.debug("end...{}", latch.getCount());
        }).start();
        new Thread(() -> {
            log.debug("begin...");
            sleep(1.5);
            latch.countDown();
            log.debug("end...{}", latch.getCount());
        }).start();
        log.debug("waiting...");
        latch.await();
        log.debug("wait end...");
    }
}

改进

相比于 join 方法,CountdownLatch 可以配合线程池使用,无需等待线程结束,这就是 CountdownLatch 的高级之处

public class TestCountDownLatch {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        test5();
    }

    private static void test5() {
        CountDownLatch latch = new CountDownLatch(3);
        ExecutorService service = Executors.newFixedThreadPool(4); // 固定线程数线程池
        service.submit(() -> {
            log.debug("begin...");
            sleep(1); // 模拟线程执行任务时间
            latch.countDown(); // 倒计时计数减 1
            log.debug("end...{}", latch.getCount()); // 拿到剩余 latch
        });
        service.submit(() -> {
            log.debug("begin...");
            sleep(1.5);
            latch.countDown(); // 倒计时计数减 1
            log.debug("end...{}", latch.getCount());
        });
        service.submit(() -> {
            log.debug("begin...");
            sleep(2);
            latch.countDown(); // 倒计时计数减 1
            log.debug("end...{}", latch.getCount());
        });
        service.submit(()->{ // 等待 3 个线程干完了做汇总操作
            try {
                log.debug("waiting...");
                latch.await(); // latch 在减为 0 之前,会一直在这阻塞
                log.debug("wait end...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}

输出

17:12:08.379 c.TestCountDownLatch [pool-1-thread-3] - begin...
17:12:08.382 c.TestCountDownLatch [pool-1-thread-4] - waiting...
17:12:08.381 c.TestCountDownLatch [pool-1-thread-2] - begin...
17:12:08.379 c.TestCountDownLatch [pool-1-thread-1] - begin...
17:12:09.397 c.TestCountDownLatch [pool-1-thread-1] - end...2
17:12:09.900 c.TestCountDownLatch [pool-1-thread-2] - end...1
17:12:10.402 c.TestCountDownLatch [pool-1-thread-4] - wait end...
17:12:10.403 c.TestCountDownLatch [pool-1-thread-3] - end...0

CountdownLatch 应用

模拟一下 5 V 5 游戏等待玩家加载完成,游戏正式开始的场景

    private static void test2() throws InterruptedException {
        AtomicInteger num = new AtomicInteger(0);
        ExecutorService service = Executors.newFixedThreadPool(10, (r) -> {
            return new Thread(r, "t" + num.getAndIncrement());
        });
        CountDownLatch latch = new CountDownLatch(10);
        String[] all = new String[10];
        Random r = new Random();
        for (int j = 0; j < 10; j++) { // 模拟 10 个玩家加载游戏
            int x = j; // lambda 表达式只能引用局部的常量,变量不行,lambda 表达式实际上是内部类,默认是 final 修饰,不加修饰符也是 final 修饰
            service.submit(() -> {
                for (int i = 0; i <= 100; i++) {
                    try {
                        Thread.sleep(r.nextInt(600)); // 模拟玩家网络延时
                    } catch (InterruptedException e) {
                    }
                    all[x] = Thread.currentThread().getName() + "(" + (i + "%") + ")";
                    System.out.print("\r" + Arrays.toString(all)); // \r 后一次打印结果会覆盖掉前一次打印结果
                }
                latch.countDown(); // 一个玩家加载完成后,计数减 1
            });
        }
        latch.await(); // 等待玩家加载游戏
        System.out.println("\n游戏开始...");
        service.shutdown();
    }

CountdownLatch 应用2

现在有 3 个服务分别部署在 3 台服务器上,现在使用远程 RPC 调用获取商品,订单和物流信息

// 控制层
@RestController
public class TestCountDownlatchController {
    /*
    模拟 3 个微服务异步编排
    代码先不用理解,后面 Spring 会讲到,先熟悉就行
     */

    /**
     * 订单信息
     * @param id
     * @return
     */
    @GetMapping("/order/{id}")
    public Map<String, Object> order(@PathVariable int id) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("total", "2300.00");
        sleep(2000);
        return map;
    }

    /**
     * 商品信息
     * @param id
     * @return
     */
    @GetMapping("/product/{id}")
    public Map<String, Object> product(@PathVariable int id) {
        HashMap<String, Object> map = new HashMap<>();
        if (id == 1) {
            map.put("name", "小爱音箱");
            map.put("price", 300);
        } else if (id == 2) {
            map.put("name", "小米手机");
            map.put("price", 2000);
        }
        map.put("id", id);
        sleep(1000);
        return map;
    }

    /**
     * 物流信息
     * @param id
     * @return
     */
    @GetMapping("/logistics/{id}")
    public Map<String, Object> logistics(@PathVariable int id) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("name", "中通快递");
        sleep(2500);
        return map;
    }

    private void sleep(int millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
// 线程池 + Future 方式
    private static void test3() throws InterruptedException, ExecutionException {
        RestTemplate restTemplate = new RestTemplate();
        log.debug("begin");
        ExecutorService service = Executors.newCachedThreadPool(); // 缓存线程池,全员救急线程
        CountDownLatch latch = new CountDownLatch(4);
        Future<Map<String,Object>> f1 = service.submit(() -> {
            Map<String, Object> response = restTemplate.getForObject("http://localhost:8080/order/{1}", Map.class, 1);
            return response;
        });
        Future<Map<String, Object>> f2 = service.submit(() -> {
            Map<String, Object> response1 = restTemplate.getForObject("http://localhost:8080/product/{1}", Map.class, 1);
            return response1;
        });
        Future<Map<String, Object>> f3 = service.submit(() -> {
            Map<String, Object> response1 = restTemplate.getForObject("http://localhost:8080/product/{1}", Map.class, 2);
            return response1;
        });
        Future<Map<String, Object>> f4 = service.submit(() -> {
            Map<String, Object> response3 = restTemplate.getForObject("http://localhost:8080/logistics/{1}", Map.class, 1);
            return response3;
        });

        System.out.println(f1.get());
        System.out.println(f2.get());
        System.out.println(f3.get());
        System.out.println(f4.get()); // get 方法会等待结果返回再往下运行
        log.debug("执行完毕");
        service.shutdown();
    }

输出结果略

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值