这里以懒汉式创建对象举例
代码路线:从最简单的单线程--->多线程同步方法(synchronized)--->同步块--->同步块的改进(双重检查)
简单说明:同步方法和同步块效率大致相同,通过双重检查的模式能最多限度提高效率。
package synchronize;
/**
* 单例模型
* 懒汉式:double checking解决多线程创建对象
* @author john
*
*/
public class SynDemo3 {
/**
* @param args
*/
public static void main(String[] args) {
/* //单线程
Jvm jvm1=Jvm.getInstance();
Jvm jvm2=Jvm.getInstance();
System.out.println(jvm1);
System.out.println(jvm2);
*/
JvmThread thread1=new JvmThread(100);
JvmThread thread2=new JvmThread(500);
thread1.start();
thread2.start();
}
}
class JvmThread extends Thread{
private long time;
public JvmThread(){
}
public JvmThread(long time){
this.time=time;
}
public void run(){
try {
System.out.println(Thread.currentThread().getName()+"--->创建"+Jvm.getInstance3(time));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Jvm{
private static Jvm instance =null;
//构造器私有化
private Jvm(){
}
public static Jvm getInstance(long time) throws InterruptedException{
if(null==instance){
Thread.sleep(time); //放大错误
instance=new Jvm();
}
return instance;
}
//同步方法
public static synchronized Jvm getInstance1(long time) throws InterruptedException{
if(null==instance){
Thread.sleep(time); //放大错误
instance=new Jvm();
}
return instance;
}
//同步块
public static Jvm getInstance2(long time) throws InterruptedException{
//效率不高与getInstance1相同,存在对象也需要等待
synchronized (Jvm.class) {
if(null==instance){
Thread.sleep(time); //放大错误
instance=new Jvm();
}
return instance;
}
}
//同步块改进
public static Jvm getInstance3(long time) throws InterruptedException{
//效率高,提高已经存在对象的访问效率
if(null==instance){
synchronized (Jvm.class) {
if(null==instance){
Thread.sleep(time); //放大错误
instance=new Jvm();
}
return instance;
}
}
return instance;
}
}