单例模式
Posted liushisaonian
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单例模式相关的知识,希望对你有一定的参考价值。
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(); } }
以上是关于单例模式的主要内容,如果未能解决你的问题,请参考以下文章