(单例设计模式中)懒汉式与饿汉式在多线程中的不同
生活随笔
收集整理的這篇文章主要介紹了
(单例设计模式中)懒汉式与饿汉式在多线程中的不同
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/*目的:分析一下單例設計模式中,懶漢式與餓漢式在多線程中的不同!開發時我們一般選擇餓漢式,因為它簡單明了,多線程中不會出現安全問題!而餓漢式需要我們自己處理程序中存在的安全隱患,但是餓漢式的程序技術含量更高!
*/
/* class SinglePerson implements Runnable{private static SinglePerson ss = new SinglePerson("hjz", 22);//惡漢式private int age;private String name;private int count;private SinglePerson(String name, int age){this.age = age;this.name = name;}private SinglePerson(){age = 10;name = " ";}public static SinglePerson getInstance(){return ss;}public String getName(){return name;}public int getAge(){return age;}public void setIntroduceCount(){++count;}public int getIntroduceCount(){return count;}public synchronized void run(){ss.setIntroduceCount();try{Thread.sleep(20);}catch(InterruptedException e){}System.out.println("this is " + ss.getName() + " " + ss.getAge() + " 被介紹的次數是:" + ss.getIntroduceCount());}} */class SinglePerson implements Runnable{private static SinglePerson ss = null;//懶漢式private int age;private String name;private int count;private SinglePerson(String name, int age){this.age = age;this.name = name;count=0;}private SinglePerson(){age = 10;name = " ";}/*public static SinglePerson getInstance(){if(ss==null){//單例設計模式中,懶漢式在多線程中的缺憾啊!可能不能保證對象的唯一性try{Thread.sleep(10);}catch(InterruptedException e){}ss = new SinglePerson("hjz", 22);}return ss;}*//* public static synchronized SinglePerson getInstance(){//保證了對象的唯一性,也就是安全性保證了!但是每當調用該函數時if(ss==null){ //都要判斷一下同步鎖對象,降低了程序的效率!try{Thread.sleep(10);}catch(InterruptedException e){}ss = new SinglePerson("hjz", 22);}return ss;} */public static SinglePerson getInstance(){//這就是懶漢式的安全又效率的代碼!if(ss==null){//這一句是必須判斷的!synchronized(SinglePerson.class){//這一句只是其他的線程訪問時判斷if(ss==null){try{Thread.sleep(10);}catch(InterruptedException e){}ss = new SinglePerson("hjz", 22);}}}return ss;}public String getName(){return name;}public int getAge(){return age;}public void setIntroduceCount(){++count;}public int getIntroduceCount(){return count;}public synchronized void run(){ss.setIntroduceCount();System.out.println("this is " + ss.getName() + " " + ss.getAge() + " 被介紹的次數是:" + ss.getIntroduceCount());}
}class OtherThread extends Thread{public void run(){SinglePerson.getInstance().run();}
}public class Test{public static void main(String[] args){new OtherThread().start();new OtherThread().start();new OtherThread().start();new Thread(SinglePerson.getInstance()).start();}
}
轉載于:https://www.cnblogs.com/hujunzheng/p/3876539.html
總結
以上是生活随笔為你收集整理的(单例设计模式中)懒汉式与饿汉式在多线程中的不同的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为什么社会主义国家治安好
- 下一篇: android 版本更新工具类_报表分析