加权随机数 public class WeightRandom { public static Map servers = new HashMap (); static{ servers.put("192.168.20.101", 1); servers.put("192.168.20.102", 2); servers.put("192.168.20.103", 3); servers.put("192.168.20.104", 4); } public
public class WeightRandom { public static Mapservers = new HashMap (); static{ servers.put("192.168.20.101", 1); servers.put("192.168.20.102", 2); servers.put("192.168.20.103", 3); servers.put("192.168.20.104", 4); } public static String selectServer(Map servers){ if(servers == null || servers.size() == 0) return null; Integer sum = 0; Set > entrySet = servers.entrySet(); Iterator > iterator = entrySet.iterator(); while(iterator.hasNext()){ sum += iterator.next().getValue(); } Integer rand = new Random().nextInt(sum) + 1; for(Map.Entry entry : entrySet){ rand -= entry.getValue(); if(rand <=0){ return entry.getKey(); } } return null; } public static void main(String[] args){ Map map = new HashMap (); String key = null; for(int i = 0; i < 1000; i++){ key = selectServer(servers); if(map.containsKey(key)){ map.put(key, map.get(key) + 1); }else{ map.put(key, 1); } } for(String key1 : map.keySet()){ System.out.println(key1 + " " + map.get(key1)); } } }