Java 多线程中的 单例设计模式(懒汉式)

/**

*单例设计模式

*确保一个类只有一个对象

*懒汉式double_checking(双重检查),先判断,再执行

*1、声明一个私有静态变量这里懒得创建对象instance=null;

*2、构造器私有化,避免外部直接创对象

*3、创建一个对外的共有的静态方法访问该变量,如果没有对象就创建一个该对象

*/

publicclassSingletonPattern{

publicstaticvoidmain(String[]args){

JvmThreadthread1=newJvmThread(100);

JvmThreadthread2=newJvmThread(500);

thread1.start();

thread2.start();

}

}

 

classJvmThreadextendsThread{

privatelongtime;

 

publicJvmThread(){

}

 

publicJvmThread(longtime){

this.time=time;

}

 

@Override

publicvoidrun(){

System.out.println(Thread.currentThread().getName()+"--->创建:"+Jvm.getInstance(time));

}

}

 

/**

*单例设计模式

*确保一个类只有一个对象

*懒汉式double_checking(双重检查),先判断,再执行

*1、声明一个私有静态变量这里懒得创建对象instance=null;

*2、构造器私有化,避免外部直接创对象

*3、创建一个对外的共有的静态方法访问该变量,如果没有对象就创建一个该对象

*/

classJvm{

//*1、声明一个私有静态变量

privatestaticJvminstance=null;

 

//*2、构造器私有化,避免外部直接创对象

privateJvm(){

}

 

//*3、创建一个对外的共有的静态方法访问该变量,如果没有对象就创建一个该对象

publicstaticJvmgetInstance(longtime){

/*

synchronized(Jvm.class){//每个线程都在等待效率不高,因为synchronized块这个要花时间等

if(null==instance){

try{

Thread.sleep(time);

}catch(InterruptedExceptione){

e.printStackTrace();

}

instance=newJvm();

}

returninstance;

}*/

if(null==instance){//低效率的改良版double_checking(双重检查),先判断,再执行

synchronized(Jvm.class){

if(null==instance){

try{

Thread.sleep(time);

}catch(InterruptedExceptione){

e.printStackTrace();

}

instance=newJvm();

}

returninstance;

}

}

returninstance;

}

 

//*3、创建一个对外的共有的静态方法访问该变量,如果没有对象就创建一个该对象

publicstaticsynchronizedJvmgetInstance2(longtime){

if(null==instance){

try{

Thread.sleep(time);

}catch(InterruptedExceptione){

e.printStackTrace();

}

instance=newJvm();

}

returninstance;

}

 

//*3、创建一个对外的共有的静态方法访问该变量,如果没有对象就创建一个该对象

publicstaticsynchronizedJvmgetInstance1(longtime){

if(null==instance){

try{

Thread.sleep(time);

}catch(InterruptedExceptione){

e.printStackTrace();

}

instance=newJvm();

}

returninstance;

}

}

猜你喜欢

转载自blog.csdn.net/qq_40990854/article/details/81211801