首页 > 其他 > 详细

按权重分配任务

时间:2018-05-15 20:24:53      阅读:250      评论:0      收藏:0      [点我收藏+]
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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!