线程安全的计数器类Counter

类别:Java 点击:0 评论:0 推荐:

可向该计数器对象中添加对象,相等的对象(通过equals()方法比较是否相等)的个数被保存。可获取其中某个对象的个数,也可以获取个数最多的对象及其个数。可用于多线程环境。如有不妥之处,欢迎指正。
import java.util.*;

public final class Counter{

    private Hashtable data = new Hashtable();
    private Set maxObject = Collections.synchronizedSet(new HashSet());
    private volatile int maxCount;

    public boolean contains(Object object){
        return data.containsKey(object);
    }

    public synchronized void add(Object object){
        int count = 0;
        if (contains(object)){
            count = count(object);
        }
        data.put(object, new Integer(++count));
        if (maxCount <= count){
            if (maxCount < count) maxObject.clear();
            maxObject.add(object);
            maxCount = count;
        }
    }

    public int count(Object object){
        return ((Integer)data.get(object)).intValue();
    }

    public synchronized void clear(){
        data.clear();
        maxObject.clear();
        maxCount = 0;
    }

    public Object[] maxObject(){
        return maxObject.toArray();
    }

    public synchronized int maxCount(){
        return maxCount;
    }

    public String toString(){
        Enumeration keys = data.keys();
        Enumeration values = data.elements();
        String res = "";
        while (keys.hasMoreElements()){
            res += keys.nextElement().toString() + "="
                    + values.nextElement().toString() + ",";
        }
        res += "maxObject=[";
        Iterator maxKeys = maxObject.iterator();
        while (maxKeys.hasNext())
            res += maxKeys.next().toString() + ",";
        if (res.indexOf(",") > -1) res = res.substring(0, res.length() - 1);
        res += "],maxCount=" + maxCount;
        return res.toString();
    }

}

本文地址:http://com.8s8s.com/it/it12494.htm