懒汉式单例--双重检测锁实现线程安全

Football2.java

/**
 * 懒汉式单例
 * 用的时候再创建一个对象,线程不安全
 * @author Administrator
 *
 */
class FootBall2 {
        private static int count;
        private static FootBall2 fb;

	private FootBall2(){
            System.out.println("初始化" + (count++) + "次");
        }
	
	public  static FootBall2 getFootBall(){
		if(fb == null){
			synchronized (FootBall2.class) {
				if(fb == null){					
					fb = new FootBall2();				
				}
			}
		}
		return fb;
	}
}

测试类SinglerTest2.j:

public class SinglerTest2 {
	public static void main(String[] args) {
		for (int i = 0; i < 100; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					System.out.println(Thread.currentThread().getName() + ":" + FootBall2.getFootBall());
				}
			}).start();
		}
	}
}

结果:

初始化0次
Thread-5:dan_li.FootBall2@67deccdf
Thread-1:dan_li.FootBall2@67deccdf

...

猜你喜欢

转载自blog.csdn.net/Tanganq/article/details/83417499
今日推荐