首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

巧用ENUM 兑现 Thread-safe Singleton

2012-08-31 
巧用ENUM 实现 Thread-safe Singleton其实Enum 类本身就是一个Class 唯一不同的就是这个class的构造函数是

巧用ENUM 实现 Thread-safe Singleton

其实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

热点排行