一、单例模式的两种线程安全方式
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 饿汉式的单例模式
*/
class Singleton{
private Singleton() {};
private static Singleton instance=new Singleton();
public static Singleton getInstance() {
return instance;
}
}
/**
* 懒汉式的单例模式
*/
class Singleton2{
private Singleton2() {};
private static volatile Singleton2 instance;
public static Singleton2 getInstance() {
if(instance==null) {
synchronized(Singleton2.class) {
if(instance==null)
instance=new Singleton2();
}
}
return instance;
}
}
public class Main {
public static void main(String[] args) {
ExecutorService executor=Executors.newFixedThreadPool(20);
for(int i=0;i!=20;i++) {
executor.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+": "+Singleton2.getInstance());
}
});
}
executor.shutdown();
}
}
二、结果