JAVA技巧:加同步鎖的單例模式代碼

字號(hào):

/*
    *單例模式
    *單例模式,保證一個(gè)類僅有一個(gè)實(shí)例,并提供一個(gè)訪問它的全局訪問點(diǎn)。
    *加同步鎖的單例模式,適合在多線程中使用。
    */
    class Singleton{
    private static Singleton instance;
    private Singleton(){}//構(gòu)造函數(shù)為private,外類不能使用new來創(chuàng)建立此類的實(shí)例
    public static Singleton getInstance(){//獲得實(shí)例的全局訪問點(diǎn)
    System.out.println("進(jìn)入外層");
    if (instance==null){
    synchronized(Singleton.class){
    if(instance==null){
    instance=new Singleton();
    System.out.println("進(jìn)入里層");
    }//end inner if
    }//end synchronized
    }//end outter if
    return instance;
    }//end getInstance()
    }
    class Instance extends Thread{
    static int count=1;
    public void run(){
    System.out.println("第"+ count++ +"次調(diào)用同一個(gè)實(shí)例!");
    Singleton s1=Singleton.getInstance();
    }//end run
    public static void main(String []args){
    for( int i=1;i<5;i++){
    Instance thread1=new Instance();
    thread1.start();
    }
    }//end main
    }
    運(yùn)行結(jié)果:
    第1次調(diào)用同一個(gè)實(shí)例!
    進(jìn)入外層
    進(jìn)入里層
    第2次調(diào)用同一個(gè)實(shí)例!
    進(jìn)入外層
    第3次調(diào)用同一個(gè)實(shí)例!
    進(jìn)入外層
    第4次調(diào)用同一個(gè)實(shí)例!
    進(jìn)入外層