您好,登錄后才能下訂單哦!
怎樣寫出一個線程安全的單例模式
package com.chendan.mianshi;
/**
*
*
* @Description
* @author ChenDan 624665255@qq.com
* @date 2019年8月4日下午8:47:13
*
*/
public class MianShiTest2 {
public static void main(String[] args) {
// com.chendan.mianshi.SingleTon@1c53fd30
// com.chendan.mianshi.SingleTon@1c53fd30
// 可以看到結果一樣
getInstanceEhs();
// com.chendan.mianshi.SingleTon2@282ba1e
// com.chendan.mianshi.SingleTon2@282ba1e
getInstanceLhs();
//com.chendan.mianshi.SingleTon3@f5f2bb7
//com.chendan.mianshi.SingleTon3@f5f2bb7
getInstanceLhs2();
}
// 餓漢式方法
public static void getInstanceEhs() {
// 調用GetInstance直接返回一個instance對象,且是唯一的
SingleTon instance1 = SingleTon.getInstance();
SingleTon instance2 = SingleTon.getInstance();
// com.chendan.mianshi.SingleTon@1c53fd30
System.out.println(instance1);
// com.chendan.mianshi.SingleTon@1c53fd30
System.out.println(instance2);
}
// 懶漢式方法
public static void getInstanceLhs() {
// 調用getInstance直接返回一個instance對象,且是唯一的
SingleTon2 instance1 = SingleTon2.getInstance();
SingleTon2 instance2 = SingleTon2.getInstance();
// ccom.chendan.mianshi.SingleTon2@cad498c
System.out.println(instance1);
// com.chendan.mianshi.SingleTon2@cad498c
System.out.println(instance2);
}
public static void getInstanceLhs2() {
// 調用getInstance直接返回一個instance對象,且是唯一的
SingleTon3 instance1 = SingleTon3.getInstance();
SingleTon3 instance2 = SingleTon3.getInstance();
// com.chendan.mianshi.SingleTon2@cad498c
System.out.println(instance1);
// com.chendan.mianshi.SingleTon2@cad498c
System.out.println(instance2);
}
}
//餓漢式直接初始化方法
class SingleTon {
private SingleTon() {
}
// 餓漢式直接靜態初始化,保證唯一,但是初始類時就加載內存,性能稍低
private static SingleTon instance = new SingleTon();
// 創建直接返回線程方法
public static SingleTon getInstance() {
return instance;
}
}
//懶漢式靜態內部類初始化方法
class SingleTon2 {
private SingleTon2() {
}
private static class Singleton2Holder {
public final static SingleTon2 instance = new SingleTon2();
}
public static SingleTon2 getInstance() {
return Singleton2Holder.instance;
}
}
class SingleTon3 {
private SingleTon3() {
}
public static SingleTon3 instance = null;
public static SingleTon3 getInstance() {
if (instance == null) {
synchronized (SingleTon3.class) {
if (instance == null) {
instance = new SingleTon3();
}
}
}
return instance;
}
}
總結:最優方法為內部靜態類的方法,即方法2
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。