第一种:饿汉式
public class SingletonOne {
private static final int THREADS=100;
private static SingletonOne instance;
private SingletonOne(){}
static {
instance=new SingletonOne();
}
public static SingletonOne getInstance(){
return instance;
}
public static void main(String[] args) {
for (int i=0;i<THREADS;i++){
new Thread(
()-> System.out.println(getInstance().hashCode())
).start();
}
}
}
第二种:懒汉式
public class SingletonTow {
private static SingletonTow instance;
private static final int THREADS=100;
private SingletonTow(){}
public static SingletonTow getInstance(){
if (instance==null){
instance=new SingletonTow();
}
return instance;
}
public static void main(String[] args) {
for (int i=0;i<THREADS;i++){
new Thread(
()-> System.out.println(getInstance().hashCode())
).start();
}
}
}
第三种:双检锁式
public class SingletonTow {
private static volatile SingletonTow instance;
private static final int THREADS=100;
private SingletonTow(){}
public static SingletonTow getInstance(){
if (instance==null){
synchronized (SingletonTow.class){
if (instance==null){
instance=new SingletonTow();
}
}
}
return instance;
}
public static void main(String[] args) {
for (int i=0;i<THREADS;i++){
new Thread(
()-> System.out.println(getInstance().hashCode())
).start();
}
}
}
java并发编程:volatile关键字解析
第四种:静态内部类式
public class SingletonThree {
private static final int THREADS=100;
private static class Inner{
private static final SingletonThree INSTANCE=new SingletonThree();
}
private SingletonThree(){}
public static SingletonThree getInstance(){
return Inner.INSTANCE;
}
public static void main(String[] args) {
for (int i=0;i<THREADS;i++){
new Thread(
()-> System.out.println(SingletonThree.getInstance().hashCode())
).start();
}
}
}
第五种:枚举类型
public enum SingletonFour {
SINGLETON_FOUR;
public void test(){
System.out.println("hello world");
}
}
public class Main {
public static void main(String[] args) {
SingletonFour.SINGLETON_FOUR.test();
}
}