Java單例形式完成的幾種方法。本站提示廣大學習愛好者:(Java單例形式完成的幾種方法)文章只能為提供參考,不一定能成為您想要的結果。以下是Java單例形式完成的幾種方法正文
Java單例形式完成的幾種方法
單例形式很多多少書上都是這麼寫的:
public class SingleTon1 { private SingleTon1(){ } private static SingleTon1 instance = null; public static SingleTon1 getInstance(){ if(instance == null){ instance = new SingleTon1(); } return instance; } }
然則現實開辟中是不會這麼寫的,由於有一個嚴重的成績,多線程並發拜訪的時刻,能夠會發生多個實例!!
上面羅列幾個經常使用的辦法:
1.應用synchronized 症結字
package singleton; public class SingleTon1 { private SingleTon1(){ } private static SingleTon1 instance = null; //多線程成績解法一,然則效力不高!由於每次挪用都邑加鎖! public static synchronized SingleTon1 getInstance(){ if(instance == null){ instance = new SingleTon1(); } return instance; } public void print(){ System.out.println("thread_id:"+Thread.currentThread().getId()); } private static Object object = new Object(); //很奇妙的辦法,只要在null的時刻加鎖,以後就不加啦 public static SingleTon1 getInstance2(){ if(instance == null){ synchronized (object){ instance = new SingleTon1(); } } return instance; } }
2.加鎖
package singleton; import java.util.concurrent.locks.ReentrantLock; public class SingleTon2 { private SingleTon2(){ } private static ReentrantLock lock = new ReentrantLock(); private static SingleTon2 instance = null; public void print(){ System.out.println("thread_id:"+Thread.currentThread().getId()); } public static SingleTon2 getInstance2(){ if(instance == null){ lock.lock(); if(instance == null){ //留意這裡還要斷定下!! instance = new SingleTon2(); } lock.unlock(); } return instance; } }
3.應用靜態變量:
package singleton; public class SingleTon3 { public static void print(){ System.out.println("thread_id:"+Thread.currentThread().getId()); } public static Nested getNested(){ return Nested.instance; } //這個是單例創立的類 static class Nested{ private Nested(){ } static Nested instance = new Nested(); } }
以上就是經常使用的創立單例的形式:
Test測試代碼:
package singleton; import singleton.SingleTon3.Nested; public class Test2 { public static void main(String[] args) { // TODO Auto-generated method stub Nested singleton; Myrunnable mm = new Myrunnable(); Myrunnable m1 = new Myrunnable(); Myrunnable2 m2 = new Myrunnable2(); new Thread(m1).start(); new Thread(m2).start(); if(m1.singleton == m2.singleton){ //是統一個 System.out.println("是統一個"); }else{ System.out.println("不是統一個"); } } } class Myrunnable implements Runnable{ Nested singleton; @Override public void run() { // TODO Auto-generated method stub singleton = SingleTon3.getNested(); SingleTon3.print(); } } class Myrunnable2 implements Runnable{ Nested singleton; @Override public void run() { // TODO Auto-generated method stub singleton = SingleTon3.getNested(); SingleTon3.print(); } }
輸入:
是統一個
thread_id:11
thread_id:10
以上就是對Java 單例形式的材料整頓,後續持續彌補相干材料,感謝年夜家對本站的支撐!