单例和多线程

ThreadLocal概念:
线程局部变量,是一种多线程间并发访问变量的解决方案。与synchronized等加锁方法是不同,ThreadLocal完全不提供锁,而使用以空间换时间的手段,为每个线程提供变量的独立副本,以保障线程安全。
从性能上说,ThreadLocal不具有绝对的优势,在并发不是很高的时候,加锁的性能会更好,但作为一套与锁完全不管的线程安全解决方案,在高并发量或者竞争激烈的场景,使用ThreadLocal可以再在一定程度上减少锁竞争。


单例模式:
最常见的就是饥饿模式和懒汉模式,一个直接实例化对象,一个在调用方法时进行实例化对象。

单例和多线程
单例和多线程


在多线程模式中,考虑性能和线程安全问题,一般选两种经典的单例模式,有提高性能,又保证安全:
1.dubble check instan
2.static inner class

  • 第一种:
public class DubbleSingleton {

	private static DubbleSingleton ds;
	
	public static DubbleSingleton getDs(){
		if(ds == null){
			try {
				//模拟初始化对象的准备时间
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			synchronized(DubbleSingleton.class){
				if(ds == null){
					ds = new DubbleSingleton();
				}
			}
		}
		return ds;
	}
	
	public static void main(String args[]){
		
		Thread t1 = new Thread(new Runnable(){
			@Override
			public void run() {
				System.out.println(DubbleSingleton.getDs().hashCode());
			}
		},"t1");
		
		Thread t2 = new Thread(new Runnable(){
			@Override
			public void run() {
				System.out.println(DubbleSingleton.getDs().hashCode());
			}
		},"t2");
		
		Thread t3 = new Thread(new Runnable(){
			@Override
			public void run() {
				System.out.println(DubbleSingleton.getDs().hashCode());
			}
		},"t3");
	
		t1.start();
		t2.start();
		t3.start();
	}
}

输出结果:

1374939831
1374939831
1374939831

思考:
代码中加了两段的if判断,如果第二个if去掉会有区别么?(画图理解)

  • 第二种:
public class InnerSingleton {

	private static class Singleton{
		private static Singleton single = new Singleton();
	}
	
	public static Singleton getInstance(){
		return Singleton.single;
	}
}