本文讲解两方面的内容
1.枚举的使用
2.多线程中单例模式的实现
1.枚举的使用
参看http://developer.51cto.com/art/201107/275031.htm
http://www.cnblogs.com/zhaoyanjun/p/5659811.html
自定义枚举类如下
public class MyObject {    public enum Color {        RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);//枚举变量        //枚举变量的属性,和枚举变量对应        PRivate String name ;        private int index ;        //枚举类的构造方法,私有是为了防止被实例化        private Color( String name , int index ){            this.name = name ;            this.index = index ;        }        //set,get方法        public String getName() {            return name;        }        public void setName(String name) {            this.name = name;        }        public int getIndex() {            return index;        }        public void setIndex(int index) {            this.index = index;        }    }}2.多线程中单例模式的实现
(1)使用静态变量加载(饿汉式)
(2)延迟加载(懒汉式)
懒汉式中的同步问题解决:
public class MyObject {    private volatile static MyObject myObject;    public static MyObject getInstance(){        try{            if(myObject!=null){                //            }else{                Thread.sleep(3000);//模拟创建对象的准备性工作                synchronized (MyObject.class){                    //再次判断是为了保证可能有多个线程停在上面一步,为了确保只new一个实例;                    //可能当该线程第一次if时为null,在sleep过程中,刚好已经有线程new实例了,需要再次判断                    if(myObject==null){                        myObject=new MyObject();                    }                }            }        } catch (InterruptedException e) {            e.printStackTrace();        }        return myObject;    }}(3)使用静态内置类实现单例模式这个和静态变量加载相似,只是将该语句添加到内部类中
(4)使用静态代码块实现单例模式
(5)序列化与反序列化中出先new实例,破坏了单例;解决方法是在反序列化中使用readResolve()方法获取对象
(6) 使用enum枚举实现单例模式
public enum MyObject2 {    connectionFactory;//枚举变量        private Connection connection;//枚举变量的属性        private MyObject2(){        //在此处完成属性的赋值        //connection=.....    }    //返回该属性    public Connection getConnection(){        return connection;    }}如上所示,即便是多个线程获取连接,也只会有一个connection
新闻热点
疑难解答