码迷,mamicode.com
首页 > 其他好文 > 详细

按权重分配任务

时间:2018-05-15 21:01:27      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:red   res   value   nbsp   bsp   ring   cep   AC   ati   

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;
    }
}

 

按权重分配任务

标签:red   res   value   nbsp   bsp   ring   cep   AC   ati   

原文地址:https://www.cnblogs.com/zhshlimi/p/9042684.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!