单例模式分类
/**
* Author:Mr.X
* Date:2017/9/20 11:44
* Description:
*
* @1、单例模式的目的:始终保持只有一个对象
* @2、单例模式分为:饿汉式、懒汉式、登记式(可忽略)
*/
public class SingletonTest implements Runnable {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "---->" + Singleton1.getInstance());
System.out.println(Thread.currentThread().getName() + "---->" + Singleton2.getInstance());
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new SingletonTest()).start();
}
}
}
/**
* @饿汉式单例:线程安全
*/
class Singleton1 {
private Singleton1() {
}
private static final Singleton1 singleton1 = new Singleton1();
public static Singleton1 getInstance() {
return singleton1;
}
}
/**
* @懒汉式单例:线程不安全
*/
class Singleton2 {
private Singleton2() {
}
public static Singleton2 singleton2 = null;
public static Singleton2 getInstance() {
if (singleton2 == null) {
singleton2 = new Singleton2();
}
return singleton2;
}
}
让单例模式线程安全的3种方法
/**
* Author:Mr.X
* Date:2017/9/20 14:13
* Description:
* @、本例中:专门解决懒汉式的线程安全问题,分别有3中解决方案!
*/
public class SingletonTest implements Runnable {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//System.out.println(Thread.currentThread().getName() + "-->" + Singleton1.getInstance());
//System.out.println(Thread.currentThread().getName() + "-->" + Singleton2.getInstance());
System.out.println(Thread.currentThread().getName() + "-->" + Singleton3.getInstance());
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new SingletonTest()).start();
}
}
}
class Singleton1 {
private Singleton1() {
}
public static Singleton1 singleton = null;
public static synchronized Singleton1 getInstance() {
if (singleton != null) {
singleton = new Singleton1();
}
return singleton;
}
}
class Singleton2 {
private Singleton2() {
}
public static Singleton2 singleton = null;
public static Singleton2 getInstance() {
if (singleton == null) {
synchronized (Singleton2.class) {
if (singleton != null) {
singleton = new Singleton2();
}
}
}
return singleton;
}
}
class Singleton3 {
private Singleton3() {
}
private static class LazyHolder {
private static final Singleton3 INSTANCE = new Singleton3();
}
public static final Singleton3 getInstance() {
return LazyHolder.INSTANCE;
}
}