双重检查解决多线程效率问题

这里以懒汉式创建对象举例
代码路线:从最简单的单线程--->多线程同步方法(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;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值