Singleton,即單例,在Java中表示的是單例模式,所謂的單例模式,指的就是在程序中,有且僅有一個該實例對象。java
單:惟一,單獨。
例:實例對象。面試
2.1.1 直接建立實例對象(簡介明瞭)
將構造方法私有化。
提供一個static修飾的常量對象。安全
package com.qingyun.demo.single.test; import com.qingyun.demo.single.Singleton1; /** * Created with IntelliJ IDEA. * User: 李敷斌. * Date: 2020-05-11 * Time: 08:58 * Explain: */ public class TestSingleton1 { public static void main(String[] args) { Singleton1 singleton1=Singleton1.INSTANCE; System.out.println(singleton1); } }
測試代碼多線程
public static void main(String[] args) { Singleton1 singleton1=Singleton1.INSTANCE; System.out.println(singleton1); }
能夠成功建立實例對象ide
public class TestSingleton2 { public static void main(String[] args) { Singleton2 singleton2=Singleton2.INSTANCE; System.out.println(singleton2); } }
package com.qingyun.demo.single; import java.io.IOException; import java.util.Properties; /** * Created with IntelliJ IDEA. * User: 李敷斌. * Date: 2020-05-11 * Time: 08:59 * Explain: 單例模式-餓漢式(靜態代碼塊方式) */ public class Singleton3 { public static final Singleton3 INSTANCE; public String info; static{ //建立一個讀取properties的實例對象 Properties properties=new Properties(); try { properties.load(Singleton3.class.getClassLoader().getResourceAsStream("info.properties")); INSTANCE=new Singleton3(new String(properties.getProperty("info").getBytes("iso-8859-1"),"utf-8")); } catch (IOException e) { throw new RuntimeException(e); } } private Singleton3(String info){ this.info=info; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } @Override public String toString() { return "Singleton3{" + "info='" + info + '\'' + '}'; } }
2.2.1 經過定義方法,當其餘程序調用該方法時建立對象(使用與單線程,多線程條件下,可能會發生線程安全問題)性能
package com.qingyun.demo.single; /** * Created with IntelliJ IDEA. * User: 李敷斌. * Date: 2020-05-11 * Time: 09:38 * Explain: 單例模式-懶漢式(適用於單線程) * 延時建立實例,getInstance()方法的時候才建立 */ public class Singleton4 { private static Singleton4 instance; private Singleton4(){ } public static Singleton4 getInstance() { //當instance爲空的時候才須要 建立實例 (這種方式可能存在線程安全問題) if (instance==null){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } instance=new Singleton4(); } return instance; } }
測試代碼測試
package com.qingyun.demo.single.test; import com.qingyun.demo.single.Singleton4; import java.util.concurrent.*; public class Singleton4Test { public static void main(String[] args) throws ExecutionException, InterruptedException { // //單線程狀況下 不存在安全問題 // Singleton4 s1=Singleton4.getInstance(); // Singleton4 s2=Singleton4.getInstance(); // // System.out.println(s1==s2); // System.out.println(s1); // System.out.println(s2); Callable<Singleton4> callable=new Callable<Singleton4>() { @Override public Singleton4 call() throws Exception { return Singleton4.getInstance(); } }; ExecutorService es= Executors.newFixedThreadPool(2); Future<Singleton4> future1 = es.submit(callable); Future<Singleton4> future2 = es.submit(callable); Singleton4 s1 = future1.get(); Singleton4 s2 = future2.get(); System.out.println(s1==s2); System.out.println(s1); System.out.println(s2); es.shutdown(); } }
單線程執行測試代碼,不會出現問題。
多線程執行結果,以下圖:
this
能夠發現,兩個對象的hashCode值是不同的,故該方式存在線程安全問題。線程
package com.qingyun.demo.single; /** * Created with IntelliJ IDEA. * User: 李敷斌. * Date: 2020-05-11 * Time: 09:49 * Explain: 單例模式-懶漢式(使用與多線程,經過加鎖的方式解決線程安全問題) */ public class Singleton5 { private static Singleton5 instance; private Singleton5(){ } public static Singleton5 getInstance() { //爲了提升性能再加一層if判斷 if (instance==null){ synchronized(Singleton5.class){ //當instance爲空的時候才須要 建立實例 (這種方式可能存在線程安全問題) if (instance==null){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } instance=new Singleton5(); } } } return instance; } }
測試代碼:code
public class Singleton5Test { public static void main(String[] args) throws ExecutionException, InterruptedException { Callable<Singleton5> callable=new Callable<Singleton5>() { @Override public Singleton5 call() throws Exception { return Singleton5.getInstance(); } }; ExecutorService es= Executors.newFixedThreadPool(2); Future<Singleton5> future1 = es.submit(callable); Future<Singleton5> future2 = es.submit(callable); Singleton5 s1 = future1.get(); Singleton5 s2 = future2.get(); System.out.println(s1==s2); System.out.println(s1); System.out.println(s2); es.shutdown(); } }
執行結果,以下圖所示:
從執行結果中能夠很清楚的看出,經過加鎖的方式能夠解決懶漢式的線程安全問題。
package com.qingyun.demo.single.test; import com.qingyun.demo.single.Singleton6; import java.util.concurrent.*; public class Singleton6Test { public static void main(String[] args) throws ExecutionException, InterruptedException { Callable<Singleton6> callable=new Callable<Singleton6>() { @Override public Singleton6 call() throws Exception { return Singleton6.getInstance(); } }; ExecutorService es= Executors.newFixedThreadPool(2); Future<Singleton6> future1 = es.submit(callable); Future<Singleton6> future2 = es.submit(callable); Singleton6 s1 = future1.get(); Singleton6 s2 = future2.get(); System.out.println(s1==s2); System.out.println(s1); System.out.println(s2); es.shutdown(); } }
測試代碼,同3.2.2,測試結果也是線程安全的。
那麼爲何經過內部類建立實例對象就是線程安全的呢?
由於內部類,不會隨着外部類的實例而實例化,它只有在其餘地方被調用的時候纔會真正的實例化對象。
單例模式中,若是使用餓漢式,那麼經過使用枚舉的方式實現是最簡單的。
若是是使用懶漢式,那麼推薦使用靜態內部類的方式最好。
看完有什麼不懂的歡迎在下方留言評論,記得點個贊哦!