CountDownLatch使用

常用于多线程场景,待多线程都结束后方可继续主线程逻辑处理

CodeConstant 常量类

import java.util.HashMap;
import java.util.Map;

public class CodeConstant {

    public static final Map<String, Map<String, String>> CODE = new HashMap<>();

    static {
        //资产1
        CODE.put(AssetTypeEnum.ZICHAN_1.getCode(),
                new HashMap<String, String>() {{
                    put("JS", "JS1");
                    put("CHECK", "CHECK1");
                    put("PUBLISH", "PUBLISH1");
                }});
        //资产2
        CODE.put(AssetTypeEnum.ZICHAN_2.getCode(),
                new HashMap<String, String>() {{
                    put("JS", "JS1");
                    put("CHECK", "CHECK2");
                    put("PUBLISH", "PUBLISH2");
                }});
    }
}

CountDownLatchController

import com.example.demo.constant.CodeConstant;
import com.example.demo.service.TestCountDownLatchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;


@RestController
@RequestMapping("/countDownLatch")
public class CountDownLatchController {

    private static final Logger logger = LoggerFactory.getLogger(CountDownLatchController.class);

    @Autowired
    private TestCountDownLatchService downLatchService;

    @PostMapping("/test")
    public void testCountDownLatch() {
        logger.info("测试多线程开始...");
        try {
            List<String> list = Arrays.asList("zichan1", "zichan2", "zichan3");
            CountDownLatch countDownLatch = new CountDownLatch(2);
            Map<String, Map<String, String>> map = CodeConstant.CODE;
            for (String type : list) {
                downLatchService.test(type, map, countDownLatch);
            }
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.info("测试多线程结束...");
    }

}

TestCountDownLatchService 类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

@Service
public class TestCountDownLatchService {

    private static final Logger logger = LoggerFactory.getLogger(TestCountDownLatchService.class);

    @Async
    public void test(String type, Map<String, Map<String, String>> map, CountDownLatch countDownLatch) {

        Map<String, String> typeMap = map.get(type);
        if (typeMap == null) {
            countDownLatch.countDown();
            return;
        }
        try {
            logger.info("类型{}的信息{}", type, typeMap);
            for (int i = 0; i < 1000; i++) {
                for (int j = 0; j < 1000; j++) {
                    logger.debug("i*j={}", i * j);
                }
            }
        } catch (Exception e) {
            logger.error("类型{}异常:", type, e);
        } finally {
            countDownLatch.countDown();
        }
    }
}

 启动类上补充注解 @EnableAsync

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync
@SpringBootApplication
@MapperScan(basePackages = { "com.example.demo" })
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

测试结果

可以看出,主线程执行"测试多线程开始"后,开启了两个子线程,等待子线程全部完成后,主线程继续执行"测试多线程结束";

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值