public class SingletonTest {
// 定義一個私有構造方法
private SingletonTest() {
}
//定義一個靜態私有變量(不初始化,不使用final關鍵字,使用volatile保證了多線程訪問時instance變量的可見性,避免了instance初始化時其他變量屬性還沒賦值完時,被另外線程調用)
private static volatile SingletonTest instance;
//定義一個共有的靜態方法,返回該類型實例
public static SingletonTest getIstance() {
// 對象實例化時與否判斷(不使用同步代碼塊,instance不等於null時,直接返回對象,提高運行效率)
if (instance == null) {
//同步代碼塊(對象未初始化時,使用同步代碼塊,保證多線程訪問時對象在第一次創建後,不再重複被創建)
synchronized (SingletonTest.class) {
//未初始化,則初始instance變量
if (instance == null) {
instance = new SingletonTest();
}
}
}
return instance;
}
}
靜態內部類
public final class Service {
/**
* 在私有構造函數中進行一些初始配置
*/
private Service() {
}
/**
* 獲取Service
*
* @return
*/
public static Service getInstance() {
return ServiceHolder.service;
}
private static class ServiceHolder {
private static final Service service = new Service();
}
}