使用静态代码块来实现单例模式

package com.wz.thread.staticlump;
/**
 * 使用静态代码块来实现单例模式
 * @author Administrator
 *
 */
public class MyObject {
    
    private static MyObject instance = null;
    
    private MyObject() {}
    static {
        instance = new MyObject();
    }
    public static MyObject getInstance() {
        return instance;
    }

}

 

package com.wz.thread.staticlump;

public class MyThread extends Thread {
    
    @Override
    public void run() {
        super.run();
        for (int i = 0; i < 5; i++) {
            System.out.println(MyObject.getInstance().hashCode());
        }
        
    }

}

 

package com.wz.thread.staticlump;
/**
 * 输出的hascode值相同,说明是同一个对象
 * @author Administrator
 *
 */
public class Run {

    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        MyThread t3 = new MyThread();
        t1.start();
        t2.start();
        t3.start();
    }
}

posted @ 2017-11-12 17:59  庄子游世  阅读(299)  评论(0编辑  收藏  举报