流世幻羽

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1. 单例模式恶汉式

package com.ithuanyu;

public class SingletonE {

	static SingletonE singeltonE = new SingletonE();

	private SingletonE() {

	}

	public static SingletonE getSingletonE() {
		return singeltonE;
	}

}

2.懒汉式

public class Singleton {

	private Singleton() {
	}
	//懒汉式
	static Singleton singleton = null;
	

	public static Singleton getSingeton() {
		if (singleton == null) {
			synchronized (Singleton.class) {
				if (singleton == null) {
					singleton = new Singleton();
				}
			}
		}
		return singleton;
	}

	public static void main(String[] args) {
		Thread t1 = new Thread(new Runnable() {

			@Override
			public void run() {
				Singleton singeton = Singleton.getSingeton();
				System.err.println(singeton);
			}

		});
		Thread t2 = new Thread(new Runnable() {

			@Override
			public void run() {
				Singleton singeton = Singleton.getSingeton();
				System.err.println(singeton);
			}

		});
		Thread t3 = new Thread(new Runnable() {

			@Override
			public void run() {
				Singleton singeton = Singleton.getSingeton();
				System.err.println(singeton);
			}

		});
		Thread t4 = new Thread(new Runnable() {

			@Override
			public void run() {
				Singleton singeton = Singleton.getSingeton();
				System.err.println(singeton);
			}

		});
		Thread t5 = new Thread(new Runnable() {

			@Override
			public void run() {
				Singleton singeton = Singleton.getSingeton();
				System.err.println(singeton);
			}

		});
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();

	}

}

  

posted on 2018-09-23 12:32  流世幻羽  阅读(181)  评论(0编辑  收藏  举报