其实Enum 类本身就是一个Class 唯一不同的就是这个class的构造函数是private类型的。其他enum具有所有class具有的特性。
public class EnumTest {
public static void main(String args[]){
EnumTest eTest = new EnumTest();
List<Thread> threads = new ArrayList<Thread>();
for(int i=0;i<10;i++){
threads.add(new Thread(eTest.new TT()));
}
for (Thread thread : threads) {
thread.start();
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
private enum ComparableComparator implements Comparator {
INSTANCE;
/**
* Comparable based compare implementation.
*
* @param obj1 left hand side of comparison
* @param obj2 right hand side of comparison
* @return negative, 0, positive comparison value
*/
public int compare(Object obj1, Object obj2) {
return ((Comparable) obj1).compareTo(obj2);
}
}
private class TT implements Runnable{
int count=10;
@Override
public void run() {
for(int i=0;i<count;i++){
System.out.println(ComparableComparator.INSTANCE.hashCode());
}
}
}
}
这样通过调用ComparableComparator 枚举实例INSTANCE 就达到了threa-safe 的singleton