package com.sandu.ximon.admin.utils;
|
|
import org.apache.commons.lang.RandomStringUtils;
|
import org.springframework.context.annotation.Configuration;
|
|
import java.util.concurrent.TimeUnit;
|
|
import java.util.HashMap;
|
import java.util.Map;
|
import java.util.concurrent.CountDownLatch;
|
|
/**
|
* @author LiuHaoNan
|
* @date 2022/9/6
|
*/
|
@Configuration
|
public class CountDownLatchUtil {
|
private static Map<String, CountDownLatch> data = new HashMap<>();
|
|
public void countDown(String id) {
|
if (data != null && data.get(id) != null) {
|
data.get(id).countDown();
|
}
|
}
|
|
public void push(String id, CountDownLatch countDownLatch) {
|
if (data != null) {
|
data.put(id, countDownLatch);
|
}
|
}
|
|
/**
|
* 删除CountDown
|
* @param id
|
* @param countDownLatch 对象
|
* @param timeout 等待时间
|
*/
|
public void remove(String id, CountDownLatch countDownLatch, int timeout) {
|
if (countDownLatch == null) {
|
return;
|
}
|
try {
|
countDownLatch.await(timeout, TimeUnit.MILLISECONDS);
|
if (data != null) {
|
data.remove(id);
|
}
|
} catch (InterruptedException e) {
|
throw new RuntimeException(e);
|
}
|
}
|
|
/**
|
* 没有等待时间的删除
|
* @param id
|
*/
|
public void remove(String id) {
|
if (data != null) {
|
data.remove(id);
|
}
|
}
|
|
public CountDownResultUtil createCoutDown(int times) {
|
CountDownLatchUtil countDownLatchUtil = new CountDownLatchUtil();
|
CountDownLatch countDownLatch = new CountDownLatch(times);
|
//获取一个7位随机数
|
String str = RandomStringUtils.randomAlphanumeric(7);
|
countDownLatchUtil.push(str, countDownLatch);
|
return new CountDownResultUtil(str, countDownLatch);
|
}
|
}
|