java單例模式並解決懶漢式下執行緒不安全的問題
阿新 • • 發佈:2018-12-15
單例模式中分為懶漢式和餓漢式
其中,懶漢式是執行緒不安全的,當有多條執行緒同時訪問單例物件時,則會出現多執行緒臨界資源問題。
現在用多執行緒實現並解決執行緒安全問題
餓漢式
public class SigletonDemo01 { static HashSet<King> hs = new HashSet<>(); static Runnable r = new Runnable() { @Override public void run() { //獲取單例物件 King king = King.currentInstance(); //將獲取到的單例物件新增到集合中 hs.add(king); } }; public static void main(String[] args) { //需求:多條執行緒同時去獲取單例物件,然後將獲取到的單例物件新增到HashSet中 //建立多個執行緒物件,同時訪問 單例物件 for (int i = 0; i < 10000; i++) { Thread thread = new Thread(r); thread.start(); } System.out.println(hs); } }
懶漢式
public class SigletonDemo02 { static HashSet<Queue> hs = new HashSet<>(); static Runnable r = new Runnable() { @Override public void run() { // 獲取單例物件 Queue king = Queue.currentInstance(); // 將獲取到的單例物件新增到集合中 hs.add(king); } }; public static void main(String[] args) { // 建立多個執行緒物件,同時訪問 單例物件 for (int i = 0; i < 1000; i++) { Thread thread = new Thread(r); thread.start(); } System.out.println(hs); } } class Queue { private static Queue instance; private Queue() { } //使用同步程式碼塊,同步方法,以及同步鎖都可以解決 public synchronized static Queue currentInstance() { if (instance == null) { instance = new Queue(); } return instance; } }