网站公司设计,中国中铁建设集团门户网,从事网站开发需要什么,利用对象储存做网站/*目的#xff1a;分析一下单例设计模式中#xff0c;懒汉式与饿汉式在多线程中的不同#xff01;开发时我们一般选择饿汉式#xff0c;因为它简单明了#xff0c;多线程中不会出现安全问题#xff01;而饿汉式需要我们自己处理程序中存在的安全隐患#xff0c;但是饿汉… /*目的分析一下单例设计模式中懒汉式与饿汉式在多线程中的不同开发时我们一般选择饿汉式因为它简单明了多线程中不会出现安全问题而饿汉式需要我们自己处理程序中存在的安全隐患但是饿汉式的程序技术含量更高
*/
/* 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;count0;}private SinglePerson(){age 10;name ;}/*public static SinglePerson getInstance(){if(ssnull){//单例设计模式中懒汉式在多线程中的缺憾啊可能不能保证对象的唯一性try{Thread.sleep(10);}catch(InterruptedException e){}ss new SinglePerson(hjz, 22);}return ss;}*//* public static synchronized SinglePerson getInstance(){//保证了对象的唯一性也就是安全性保证了但是每当调用该函数时if(ssnull){ //都要判断一下同步锁对象降低了程序的效率try{Thread.sleep(10);}catch(InterruptedException e){}ss new SinglePerson(hjz, 22);}return ss;} */public static SinglePerson getInstance(){//这就是懒汉式的安全又效率的代码if(ssnull){//这一句是必须判断的synchronized(SinglePerson.class){//这一句只是其他的线程访问时判断if(ssnull){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