A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 七色★碎羽 中级黑马   /  2015-9-14 22:41  /  711 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

public class Single {
        private Single(){}
        private static Single s = null;
       
        public static  Single getInstance(){
                 if(s == null){
             synchronized(Single.class){       
                    if( s == null )
               
                           s = new Single();
              }       
                 }
                 return s;
        }
}

class SingleRunnable implements Runnable{
        public void run(){
                for(int x = 0 ; x < 10 ;x++){
                        Single s = Single.getInstance();
                        System.out.println(s);
                }
        }
}


public class SingleTest {
        public static void main(String[] args) {
                SingleRunnable s = new SingleRunnable();
                new Thread(s).start();
                new Thread(s).start();
        }
}


3 个回复

倒序浏览
好东西  学习了   如果有解析说明一下就好了。。。
回复 使用道具 举报
在开发中最好使用饱汉式,避免了用Synchronized关键字,为了程序的安全(只创造一个单例)造成程序性能降低
回复 使用道具 举报
饿汉式更常用啊,因为懒汉不懂饿汉饥
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马