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