(1)饿汉模式
package singleton;
/**
* 饿汉模式 多线程环境下实现单例模式
* @author zc
*
*/
public class SingletonE {
//立即加载 饿汉模式
private static SingletonE singleton=new SingletonE();
//私有化构造方法
private SingletonE() {
}
public static SingletonE getInstance() {
return singleton;
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.start();
t2.start();
t3.start();
}
}
class MyThread extends Thread{
@Override
public void run() {
System.out.println(SingletonE.getInstance().hashCode());
}
}
(2)懒汉模式
package singleton;
/**
* 双加锁机制 实现懒汉模式的多线程环境下的单例模式
* @author zc
*
*/
public class SingletonL {
private volatile static SingletonL singleton ;
private SingletonL() {
}
public static SingletonL getInstance() throws Interr