码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式

时间:2018-09-23 15:08:11      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:stat   public   oid   ati   print   vat   package   start   system   

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();

	}

}

  

单例模式

标签:stat   public   oid   ati   print   vat   package   start   system   

原文地址:https://www.cnblogs.com/liushisaonian/p/9692411.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!