通过类的字节码锁住多线程

package com.cyj.thread.manage;


public class MySynchronized2 {

	public static void main(String[] args) {
		
//		Jvm jvm1 = Jvm.getInstance();
//		Jvm jvm2 = Jvm.getInstance();
		
//		System.out.println(jvm1);//访问的是同一个类,并且这只是单线程,地址是一样的,而多线程有区别
//		System.out.println(jvm2);
		
		JvmThread jt = new JvmThread(250);
		JvmThread jt2 = new JvmThread(1000);
		
		jt.start();
		jt2.start();
	}
}

class JvmThread extends Thread{
	
	
	private long time;
	
	public JvmThread() {
		
	}
	
	public JvmThread(long time) {
		this.time = time;
	}
	
	public void run() {

		System.out.println(Thread.currentThread().getName()+"----创建----"+Jvm.getInstance2(time)); //通过getInstance不同调用不同的方法
	}
}


/**
 * 单例设计模式:确保一个类只有一个对象
 * 懒汉式(double checking)
 * 步骤:
 * 1 构造器私有化,避免外部直接创建对象
 * 2 声明私有化的静态
 * 3 创建一个对外的公共静态的方法访问该变量
 * 4 没有就创建,通过判断是否创建提升效率
 * @author Chyjrily
 *
 */
class Jvm{
	
	//声明一个私有的静态变量
	private static Jvm instance = null; //懒得创建对象,使用时创建对象
	
	//构造器私有化,避免外部直接创建对象
	private Jvm() {
		
	}
	
	//创建一个对外的公共静态方法访问该变量,如果变量没有对象,创建该对象
	public static Jvm getInstance(long time) {//getInstance是实例化对象,跟new实例化对象区别
		if(null == instance) {
			
			try {
				Thread.sleep(time); //故意延时,提高错误率
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			instance = new Jvm();
		}
		return instance;
	}
	
	public static synchronized Jvm getInstance2(long time) { 
		if(null == instance) {
			
			try {
				Thread.sleep(time); 
			} catch (InterruptedException e) { 
				e.printStackTrace();
			}
			
			instance = new Jvm();
		}
		return instance;
	}
	
	public static Jvm getInstance3(long time) { 
		
		synchronized(Jvm.class) { //锁定类的字节码信息,任何对象进来都需进行等待,哪怕已经存在对象,效率低下
			if(null == instance) {
				
				try {
					Thread.sleep(time); 
				} catch (InterruptedException e) { 
					e.printStackTrace();
				}
				
				instance = new Jvm();
			}
			return instance;
		}
		}
    public static Jvm getInstance4(long time) { 
		
    	if(null == instance) { //如果已经创建了这个对象,资源锁住,直接有返回的已经创建好的对象,提高已经创建对象的效率
    		synchronized(Jvm.class) { 
    			if(null == instance) {
    				
    				try {
    					Thread.sleep(time); 
    				} catch (InterruptedException e) { 
    					e.printStackTrace();
    				}
    				
    				instance = new Jvm();
    			}
    	}
		}
			return instance;
		}
		
}

猜你喜欢

转载自blog.csdn.net/qq_42036616/article/details/81074562