java设计模式---单例





//饿汉式
public class Single {
	private final static Single s=new Single();
	
	private Single(){
		
	}
	
	public static Single  getInstance(){
		return s;
	}
}

public class Client {
	public static void main(String[] args) {
		Single s1 = Single.getInstance();
		Single s2 = Single.getInstance();
        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());
        
        new A().t();
	}

}
//懒汉式
public class Singel2 {
  private static Singel2 s =null;
  private Singel2(){
	  
  }
  
  public synchronized static Singel2 getInstance(){
	 
	  if(s==null){
		   s=new Singel2();
	  }
	  return s;
  }
}

public class Client2 {
	public static void main(String[] args) {
		Thread ts[] = new Thread[50];
		for(int i=0;i<ts.length;i++){
			ts[i]=new UseSingle();
		}
		
		for(int i=0;i<ts.length;i++){
			ts[i].start();
		}
	}
}

class UseSingle extends Thread{
	@Override
	public void run() {
		//Single obj = Single.getInstance();//测试饿汉式
		Singel2 obj = Singel2.getInstance();//测试懒汉式
		System.out.println(obj.hashCode());
	}
}


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页