日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

(单例设计模式中)懒汉式与饿汉式在多线程中的不同

發布時間:2025/3/8 asp.net 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 (单例设计模式中)懒汉式与饿汉式在多线程中的不同 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/*目的:分析一下單例設計模式中,懶漢式與餓漢式在多線程中的不同!開發時我們一般選擇餓漢式,因為它簡單明了,多線程中不會出現安全問題!而餓漢式需要我們自己處理程序中存在的安全隱患,但是餓漢式的程序技術含量更高! */ /* 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

總結

以上是生活随笔為你收集整理的(单例设计模式中)懒汉式与饿汉式在多线程中的不同的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。