Java多線程中的單例模式兩種實現(xiàn)方式
更新時間:2017年04月30日 11:33:51 投稿:lqh
這篇文章主要介紹了Java多線程中的單例模式兩種實現(xiàn)方式的相關資料,需要的朋友可以參考下
Java多線程中的單例模式
一、在多線程環(huán)境下創(chuàng)建單例
方式一:
package com.ietree.multithread.sync; public class Singletion { private static class InnerSingletion { private static Singletion single = new Singletion(); } public static Singletion getInstance() { return InnerSingletion.single; } }
方式二:
package com.ietree.multithread.sync; public class DubbleSingleton { private static DubbleSingleton ds; public static DubbleSingleton getDs() { if (ds == null) { try { // 模擬初始化對象的準備時間... Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (DubbleSingleton.class) { if (ds == null) { // 這個判斷很重要,如果沒有那將不是單例,而是多例 ds = new DubbleSingleton(); } } } return ds; } public static void main(String[] args) { Thread t1 = new Thread(new Runnable() { @Override public void run() { System.out.println(DubbleSingleton.getDs().hashCode()); } }, "t1"); Thread t2 = new Thread(new Runnable() { @Override public void run() { System.out.println(DubbleSingleton.getDs().hashCode()); } }, "t2"); Thread t3 = new Thread(new Runnable() { @Override public void run() { System.out.println(DubbleSingleton.getDs().hashCode()); } }, "t3"); t1.start(); t2.start(); t3.start(); } }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
在Java中實現(xiàn)可見性(visibility)的主要方法詳解
這篇文章主要介紹了在Java中實現(xiàn)可見性(visibility)的主要方法詳解,在Java中,使用關鍵字volatile和使用鎖(如synchronized關鍵字或 java.util.concurrent包中的鎖)來確保對共享變量的修改在多線程環(huán)境中能夠正確地被其他線程所觀察到,需要的朋友可以參考下2023-08-08maven升級版本后報錯:Blocked mirror for repositories
本文主要介紹了maven升級版本后報錯:Blocked mirror for repositories,文中的解決方法非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-09-09java算法題解LeetCode30包含min函數(shù)的棧實例
這篇文章主要為大家介紹了java算法題解LeetCode30包含min函數(shù)的棧實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01Spring Boot 自動裝配原理及 Starter 實現(xiàn)原理解析
SpringBoot通過@SpringBootApplication注解簡化了依賴引入和配置,該注解包括@SpringBootConfiguration、@EnableAutoConfiguration和@ComponentScan三部分,感興趣的朋友跟隨小編一起看看吧2024-09-09