1. 程式人生 > >使用靜態代碼塊來實現單例模式

使用靜態代碼塊來實現單例模式

對象 代碼 over 說明 override out min .get admin

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();
}
}

使用靜態代碼塊來實現單例模式