终于知道什么是饿汉式和懒汉式了~~
- //饿汉式
- class Single{
- private static Single s=new Single();
- private Single(){
-
- }
- public static Single getSingle(){
- return s;
- }
- }
- //懒汉式
- class Single(){
- private static Single s=null;
- private Single(){
-
- }
- public static Single getSingle(){
- if(s==null){
- s=new Single();
- }
- return s;
- }
- }
- //优化后的懒汉式,很好的解决了多线程的问题
- class Single(){
- private static Single s=null;
- private Single(){
-
- }
- public static Single getSingle(){
- if(s==null){
- synchronized(Single.class);
- if(s==null){
- s=new Single();
- }
- }
- return s;
- }
- }
复制代码
|