public class TaskAlloc { private Map<String, Integer> weight; public Map<String, Integer> getWeight() { return weight; } public Map<String, Integer> getCmpltedTask() { return cmpltedTask; } public AtomicInteger getAllcodCount() { return allcodCount; } private Map<String, Integer> cmpltedTask = new ConcurrentHashMap<String, Integer>(); private AtomicInteger allcodCount = new AtomicInteger(0); public TaskAlloc(Map<String, Integer> weight) throws Exception { this.weight = weight; Integer sum = MapHelper.reduce(weight, 0, (init, current) -> init + current); if (sum != 100) { throw new Exception("权重之合必须为100"); } for (String key : weight.keySet()) { cmpltedTask.put(key, 0); } } public String alloc() { int ac = allcodCount.getAndIncrement(); String key = getMin(cmpltedTask, weight, ac); cmpltedTask.put(key, cmpltedTask.get(key) + 1); return key; } private static String getMin(Map<String, Integer> allocedRecordMap, Map<String, Integer> weightMap, Integer allocedCount) { double min = 1; String result = null; for (Map.Entry<String, Integer> entry : weightMap.entrySet()) { String key = entry.getKey(); //计算权重所占最大的比例 double maxRatio = entry.getValue() * 1.0 / 100; //计算已分配的比例 double cmpltedRatio = allocedCount == 0 ? 0 : allocedRecordMap.get(key) * 1.0 / allocedCount; double ratio = cmpltedRatio / maxRatio; if (ratio < min) { result = key; min = ratio; } } return result; } }
原文:https://www.cnblogs.com/zhshlimi/p/9042684.html